1) A user can select a gif or jpg (any size) and upload it via a standard file upload box.
On the server side I want to take the resulting file, and resize it to a fixed size (ie 640X480) and then save it to a folder for use in a flash movie, and discard the old file. Ive nveer done anything like this before in .net, any ideas where to start?
I had the same problem! Spent hours researching to try and resolve this and eventually wrote this code in VB. Works well for me, hope you find it useful.
You will need a ASPX form with a FileUpload control, a label, an image control and a button to use the code below.
Regards Sean.
Imports
System.IO
Imports System.Drawing
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub btnUpload_Click(ByVal sender
As Object,
ByVal e As System.EventArgs)
Handles btnUpload.Click
Const bmpW = 300 'New image target width
Const bmpH = 226 'New Image target height
If (FileUpload1.HasFile)
Then
'Clear the error label text
lblError.Text = ""
'Check to make sure the file to upload has a picture file format extention and set the target width and height
If (CheckFileType(FileUpload1.FileName))
Then
Dim newWidth
As Integer = bmpW
Dim newHeight
As Integer = bmpH
'Use the uploaded filename for saving without the '.' extension
Dim upName
As String = Mid(FileUpload1.FileName, 1, (InStr(FileUpload1.FileName,
".") - 1))
'Set the save path of the resized image, you will need this directory already created in your web site
Dim filePath As
String = "~/Upload/" & upName &
".png"
'Create a new Bitmap using the uploaded picture as a Stream
'Set the new bitmap resolution to 72 pixels per inch
Dim upBmp As Bitmap = Bitmap.FromStream(FileUpload1.PostedFile.InputStream)
Dim newBmp
As Bitmap = New Bitmap(newWidth, newHeight, Imaging.PixelFormat.Format24bppRgb)
newBmp.SetResolution(72, 72)
'Get the uploaded image width and height
Dim upWidth
As Integer = upBmp.Width
Dim upHeight
As Integer = upBmp.Height
Dim newX As
Integer = 0
'Set the new top left drawing position on the image canvas
Dim newY As
Integer = 0
Dim reDuce
As Decimal
'Keep the aspect ratio of image the same if not 4:3 and work out the newX and newY positions
'to ensure the image is always in the centre of the canvas vertically and horizontally
If upWidth > upHeight
Then 'Landscape picture
reDuce = newWidth / upWidth
'calculate the width percentage reduction as decimal
newHeight = Int(upHeight * reDuce)
'reduce the uploaded image height by the reduce amount
newY = Int((bmpH - newHeight) / 2)
'Position the image centrally down the canvas
newX = 0 'Picture will be full width
ElseIf upWidth < upHeight
Then 'Portrait picture
reDuce = newHeight / upHeight
'calculate the height percentage reduction as decimal
newWidth = Int(upWidth * reDuce)
'reduce the uploaded image height by the reduce amount
newX = Int((bmpW - newWidth) / 2)
'Position the image centrally across the canvas
newY = 0 'Picture will be full hieght
ElseIf upWidth = upHeight
Then 'square picture
reDuce = newHeight / upHeight
'calculate the height percentage reduction as decimal
newWidth = Int(upWidth * reDuce)
'reduce the uploaded image height by the reduce amount
newX = Int((bmpW - newWidth) / 2) 'Position the image centrally across the canvas
newY = Int((bmpH - newHeight) / 2) 'Position the image centrally down the canvas
End If
'Create a new image from the uploaded picture using the Graphics class
'Clear the graphic and set the background colour to white
'Use Antialias and High Quality Bicubic to maintain a good quality picture
'Save the new bitmap image using 'Png' picture format and the calculated canvas positioning
Dim newGraphic
As Graphics = Graphics.FromImage(newBmp)
jusmeig
Member
10 Points
12 Posts
Resizing and Compressing an image in asp.net
Feb 26, 2007 11:11 AM|LINK
Hi there,
I have a requirement to do the following:
1) A user can select a gif or jpg (any size) and upload it via a standard file upload box.
On the server side I want to take the resulting file, and resize it to a fixed size (ie 640X480) and then save it to a folder for use in a flash movie, and discard the old file. Ive nveer done anything like this before in .net, any ideas where to start?
Cheers,
Justin
Image Width gif resize jpg compression
My site: http://www.justinmeighan.com
SGWellens
All-Star
126031 Points
10310 Posts
Moderator
Re: Resizing and Compressing an image in asp.net
Feb 26, 2007 03:00 PM|LINK
//using System.Drawing; //using System.Drawing.Imaging; Bitmap OriginalBM = new Bitmap(Server.MapPath(@"~\Chrismas2004.JPG")); Size newSize = new Size(100, 100); Bitmap ResizedBM = new Bitmap(OriginalBM, newSize); ResizedBM.Save(Server.MapPath(@"~\Resized.JPG"), ImageFormat.Jpeg);My blog
smcoxon
Contributor
5455 Points
948 Posts
Re: Resizing and Compressing an image in asp.net
Mar 12, 2007 08:47 AM|LINK
I had the same problem! Spent hours researching to try and resolve this and eventually wrote this code in VB. Works well for me, hope you find it useful.
You will need a ASPX form with a FileUpload control, a label, an image control and a button to use the code below.
Regards Sean.
Imports
System.IO Imports System.Drawing Partial Class _DefaultInherits System.Web.UI.Page
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Const bmpW = 300 'New image target width
Const bmpH = 226 'New Image target height
If (FileUpload1.HasFile) Then'Clear the error label text
lblError.Text = ""
'Check to make sure the file to upload has a picture file format extention and set the target width and height
If (CheckFileType(FileUpload1.FileName)) Then
Dim newWidth As Integer = bmpW
Dim newHeight As Integer = bmpH
'Use the uploaded filename for saving without the '.' extension
Dim upName As String = Mid(FileUpload1.FileName, 1, (InStr(FileUpload1.FileName, ".") - 1))
'Set the save path of the resized image, you will need this directory already created in your web site
Dim filePath As String = "~/Upload/" & upName & ".png"
'Create a new Bitmap using the uploaded picture as a Stream
'Set the new bitmap resolution to 72 pixels per inch
Dim upBmp As Bitmap = Bitmap.FromStream(FileUpload1.PostedFile.InputStream)
Dim newBmp As Bitmap = New Bitmap(newWidth, newHeight, Imaging.PixelFormat.Format24bppRgb)
newBmp.SetResolution(72, 72)
'Get the uploaded image width and height
Dim upWidth As Integer = upBmp.Width
Dim upHeight As Integer = upBmp.Height
Dim newX As Integer = 0 'Set the new top left drawing position on the image canvas
Dim newY As Integer = 0
Dim reDuce As Decimal
'Keep the aspect ratio of image the same if not 4:3 and work out the newX and newY positions
'to ensure the image is always in the centre of the canvas vertically and horizontally
If upWidth > upHeight Then 'Landscape picture
reDuce = newWidth / upWidth
'calculate the width percentage reduction as decimal
newHeight = Int(upHeight * reDuce)
'reduce the uploaded image height by the reduce amount
newY = Int((bmpH - newHeight) / 2)
'Position the image centrally down the canvas
newX = 0 'Picture will be full width
ElseIf upWidth < upHeight Then 'Portrait picture
reDuce = newHeight / upHeight
'calculate the height percentage reduction as decimal
newWidth = Int(upWidth * reDuce)
'reduce the uploaded image height by the reduce amount
newX = Int((bmpW - newWidth) / 2)
'Position the image centrally across the canvas
newY = 0 'Picture will be full hieght
ElseIf upWidth = upHeight Then 'square picture
reDuce = newHeight / upHeight
'calculate the height percentage reduction as decimal
newWidth = Int(upWidth * reDuce)
'reduce the uploaded image height by the reduce amount
newX = Int((bmpW - newWidth) / 2) 'Position the image centrally across the canvas
newY = Int((bmpH - newHeight) / 2) 'Position the image centrally down the canvas
End If
'Create a new image from the uploaded picture using the Graphics class
'Clear the graphic and set the background colour to white
'Use Antialias and High Quality Bicubic to maintain a good quality picture
'Save the new bitmap image using 'Png' picture format and the calculated canvas positioning
Dim newGraphic As Graphics = Graphics.FromImage(newBmp)
Try
newGraphic.Clear(Color.White)
newGraphic.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
newGraphic.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
newGraphic.DrawImage(upBmp, newX, newY, newWidth, newHeight)
newBmp.Save(MapPath(filePath), Imaging.ImageFormat.Png)
'Show the uploaded resized picture in the image control
Image1.ImageUrl = filePath
Image1.Visible = True
Catch ex As Exception
lblError.Text = ex.ToString
Finally
upBmp.Dispose()
newBmp.Dispose()
newGraphic.Dispose()
End Try
Else
lblError.Text = "Please select a picture with a file format extension of either Bmp, Jpg, Jpeg, Gif or Png."
End If
End If
End Sub
Function CheckFileType(ByVal fileName As String) As Boolean
Dim ext As String = Path.GetExtension(fileName)
Select Case ext.ToLower()
Case ".gif"
Return True
Case ".png"
Return True
Case ".jpg"
Return True
Case ".jpeg"
Return True
Case ".bmp"
Return True
Case Else
Return False
End Select
End Function
End
Class
Smcoxon
No Gem is ever polished without some friction.
NNM
Participant
1414 Points
559 Posts
Re: Resizing and Compressing an image in asp.net
Apr 30, 2007 08:25 PM|LINK
smcoxon I love you! BRILLIANT BRILLIANT!! lol
Amazing code!
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========
I'll always mark your post(s) as answer when it is!
NNM
Participant
1414 Points
559 Posts
Re: Resizing and Compressing an image in asp.net
Apr 30, 2007 08:25 PM|LINK
smcoxon I love you! BRILLIANT BRILLIANT!! lol
Amazing code!HOLY
SHIT========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========
I'll always mark your post(s) as answer when it is!
smcoxon
Contributor
5455 Points
948 Posts
Re: Resizing and Compressing an image in asp.net
May 05, 2007 04:35 PM|LINK
Glad you liked it!
Have fun [:)]
Smcoxon
No Gem is ever polished without some friction.
smcoxon
Contributor
5455 Points
948 Posts
Re: Resizing and Compressing an image in asp.net
May 05, 2007 04:36 PM|LINK
Glad you liked it!
Have fun [:)]
Smcoxon
No Gem is ever polished without some friction.
NNM
Participant
1414 Points
559 Posts
Re: Resizing and Compressing an image in asp.net
May 07, 2007 05:54 AM|LINK
The triple post was an accident... I have a mouse that causes uncontrolled postbacks! lol
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========
I'll always mark your post(s) as answer when it is!
smcoxon
Contributor
5455 Points
948 Posts
Re: Resizing and Compressing an image in asp.net
May 07, 2007 08:16 PM|LINK
Funny the same happened to me! I didn't mean to send you two replies, honest.
Have fun.
Smcoxon
Smcoxon
No Gem is ever polished without some friction.
mjhufford
Member
447 Points
119 Posts
Re: Resizing and Compressing an image in asp.net
May 17, 2007 08:09 PM|LINK
Great post, thanks! [:D]
I needed unique file names as we have many files that get uploaded and don't want anyone to overwrite another. So I changed this:
To this:
Basically changes the name of the file to a timestamp to keep it unique.~Ralph Parlette