echo4sos
Registered: 01/20/06
Posts: 236
|
|
|
Reply with quote | #1 |
Here is some basic code to resize an image upon upload. Since many of us don't want our users uploading HUGE files, we can constrain the size, width and height. This is pretty straight forward. Example is written in VB. For starters, this code goes in your page behind file (yourpage.aspx.vb) ... ***Replace YOUR_IMAGE_FIELD_NAME with the name of your own image upload field***
Code:
Public Sub SaveButton_Click(ByVal sender As Object, ByVal args As EventArgs)
' Click handler for SaveButton.
' Customize by adding code before the call or replace the call to the Base function with your own code.
If Not YOUR_IMAGE_FIELD_NAME.HasFile Then
SaveButton_Click_Base(sender, args)
Else
If YOUR_IMAGE_FIELD_NAME.HasFile Then
Dim filepath As String = YOUR_IMAGE_FIELD_NAME.PostedFile.FileName
Dim fileExt As String = LCase(System.IO.Path.GetExtension(YOUR_IMAGE_FIELD_NAME.FileName))
Dim myUpload As HttpPostedFile = YOUR_IMAGE_FIELD_NAME.PostedFile
If (fileExt = ".gif" Or fileExt = ".jpg" Or fileExt = ".bmp") And YOUR_IMAGE_FIELD_NAME.PostedFile.ContentLength < 500000 Then
Try
SaveButton_Click_Base(sender, args)
Catch ex As Exception
YOUR_IMAGE_FIELD_NAME_Label.Text = "ERROR: " & ex.Message.ToString() & ""
End Try
Else
YOUR_IMAGE_FIELD_NAME_Label.Text = "Only .gif, .jpg or .bmp files are allowed!
Also, images must be less than 500kb."
End If
End If
End If
' NOTE: If the Base function redirects to another page, any code here will not be executed.
End Sub
*Replace the amp; with actual & if copying code from here* Basically, we are letting the user know that the image size cannot exceed 500kb in size, and it can only be .gif, .jpg or .bmp. If the user attempts to upload an image that doesn't comply, we set the image label to notify the user. You can change these values to suit your own application needs.
Next, insert this code in the yourpage.controls.vb file... ***Replace YOUR_IMAGE_FIELD_NAME with the name of your own image upload field***
Code:
'This is where we resize the uploaded image before saving to the database
Public Overrides Sub GetUIdata()
MyBase.GetUIData() ' this calls the base apply of the user data
Const bmpW As Integer = 300 'New image target width
Const bmpH As Integer = 325 'New Image target height
If YOUR_IMAGE_FIELD_NAME.HasFile Then
Dim newWidth As Integer = bmpW
Dim newHeight As Integer = bmpH
Dim Pic() As Byte = Me.DataSource.YOUR_IMAGE_FIELD_NAME
' Convert to image for resizing
Dim Img As Bitmap = Nothing
Img = CType(Bitmap.FromStream(New MemoryStream(Pic, 0, Pic.Length - 1)), Drawing.Bitmap)
Dim newImg As Bitmap = New Bitmap(newWidth, newHeight, Imaging.PixelFormat.Format24bppRgb)
newImg.SetResolution(72, 72)
'Get the uploaded image width and height
Dim upWidth As Integer = Img.Width
Dim upHeight As Integer = Img.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 center of the canvas vertically and horizontally
If upWidth > upHeight Then 'Landscape picture
reDuce = CDec(newWidth / upWidth)
'calculate the width percentage reduction as decimal
newHeight = CInt(Int(upHeight * reDuce))
'reduce the uploaded image height by the reduce amount
newY = CInt(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 = CDec(newHeight / upHeight)
'calculate the height percentage reduction as decimal
newWidth = CInt(Int(upWidth * reDuce))
'reduce the uploaded image height by the reduce amount
newX = CInt(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 = CDec(newHeight / upHeight)
'calculate the height percentage reduction as decimal
newWidth = CInt(Int(upWidth * reDuce))
'reduce the uploaded image height by the reduce amount
newX = CInt(Int((bmpW - newWidth) / 2)) 'Position the image centrally across the canvas
newY = CInt(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 color to white
'Use Antialias and High Quality Bicubic to maintain a good quality picture
'Save the new bitmap image using 'jpg' picture format and the calculated canvas positioning
Dim newGraphic As Graphics = Graphics.FromImage(newImg)
newGraphic.Clear(Color.White)
newGraphic.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
newGraphic.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
newGraphic.DrawImage(Img, newX, newY, newWidth, newHeight)
Dim stream As MemoryStream = New MemoryStream
newImg.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg)
Me.DataSource.YOUR_IMAGE_FIELD_NAME = stream.ToArray ' assign back to picture
stream.Close()
Img.Dispose()
newImg.Dispose()
newGraphic.Dispose()
End If
This is where we are actually resizing the image before posting to the database. If the user uploads a picture larger than 300x325 it will automatically downsize accordingly. If the user uploads a picture smaller than 300x325 it will automatically upsize accordingly. This will also adjust the values based on orientation (portrait or landscape). It will also keep all aspect ratio, so as not to distort the image. You can change the constants (width and height) figures to suit your own application needs.
***IMPORTANT - You MUST have the System.IO and System.Drawing Imports Statements on BOTH pages*** Hope this helps many of you fellow IS developers!
-Bill
|
| |
JimiJ
MVP Developer
Registered: 03/30/05
Posts: 3,648
| |
echo4sos
Registered: 01/20/06
Posts: 236
|
|
|
Reply with quote | #3 | Hey Jimi,
Not yet. I have only used this for a "one-time" upload. It would be interesting to revisit this with multiple uploads. I'll have to find the time to do so though!
 |
| |
germ
MVP Consultant
Registered: 08/07/07
Posts: 83
| |
jtejada Registered: 02/19/09
Posts: 1
|
|
|
Reply with quote | #5 | Can you Help me? I have an erro using this magnific code. When i insert the resizing code i get an compialtion error in the first line "Public Overrides Sub GetUIdata()" The instruction is not valid in a namespace I've insert this code in the mypage.controls.vb in "section 1: Place your customizations here" Thanks |
| |
miles
MVP Consultant
Registered: 10/15/03
Posts: 2,254
|
|
|
Reply with quote | #6 | your subroutine must be contained within a class definition in order to work. Look a little farther into Section 1, and you should see class definitions for each of your panels etc..
HTH, __________________ Miles Gibson, I.S.P., ITCP
Iron Speed MVP
Senior Consultant, Principal,
Milestone Software
http://www.milesgibson.net
http://www.milestone.ca |
| |
pieterdebeer Registered: 07/01/09
Posts: 3
| |
JimiJ
MVP Developer
Registered: 03/30/05
Posts: 3,648
| |
pieterdebeer Registered: 07/01/09
Posts: 3
| |
pieterdebeer Registered: 07/01/09
Posts: 3
|
|
|
Reply with quote | #10 |
I have tried the generator without success. I did however find a converter that gives me the following code.
// This is where we resize the uploaded image before saving to the database public override void GetUIdata() { base.GetUIData(); // this calls the base apply of the user data const int bmpW = 300; // New image target width const int bmpH = 325; // New Image target height if (YOUR_IMAGE_FIELD_NAME.HasFile) { int newWidth = bmpW; int newHeight = bmpH; byte[] Pic = this.DataSource.YOUR_IMAGE_FIELD_NAME; // Convert to image for resizing Bitmap Img = null; Img = ((Drawing.Bitmap)(Bitmap.FromStream(new MemoryStream(Pic, 0, (Pic.Length - 1))))); Bitmap newImg = new Bitmap(newWidth, newHeight, Imaging.PixelFormat.Format24bppRgb); newImg.SetResolution(72, 72); // Get the uploaded image width and height int upWidth = Img.Width; int upHeight = Img.Height; int newX = 0; // Set the new top left drawing position on the image canvas int newY = 0; Decimal reDuce; // 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 center of the canvas vertically and horizontally if ((upWidth > upHeight)) { // Landscape picture reDuce = Decimal.Parse((newWidth / upWidth)); newHeight = int.Parse(Int((upHeight * reDuce))); newY = int.Parse(Int(((bmpH - newHeight) / 2))); newX = 0; // Picture will be full width } else if ((upWidth < upHeight)) { // Portrait picture reDuce = Decimal.Parse((newHeight / upHeight)); newWidth = int.Parse(Int((upWidth * reDuce))); newX = int.Parse(Int(((bmpW - newWidth) / 2))); newY = 0; // Picture will be full hieght } else if ((upWidth == upHeight)) { // square picture reDuce = Decimal.Parse((newHeight / upHeight)); newWidth = int.Parse(Int((upWidth * reDuce))); newX = int.Parse(Int(((bmpW - newWidth) / 2))); newY = int.Parse(Int(((bmpH - newHeight) / 2))); } // Create a new image from the uploaded picture using the Graphics class // Clear the graphic and set the background color to white // Use Antialias and High Quality Bicubic to maintain a good quality picture // Save the new bitmap image using 'jpg' picture format and the calculated canvas positioning Graphics newGraphic = Graphics.FromImage(newImg); newGraphic.Clear(Color.White); newGraphic.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias; newGraphic.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic; newGraphic.DrawImage(Img, newX, newY, newWidth, newHeight); MemoryStream stream = new MemoryStream(); newImg.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); this.DataSource.YOUR_IMAGE_FIELD_NAME = stream.ToArray; // assign back to picture stream.Close(); Img.Dispose(); newImg.Dispose(); newGraphic.Dispose(); } }
|
| |
timt
Iron Speed MVP Consulting Organization
Registered: 08/06/05
Posts: 1,113
|
|
|
Reply with quote | #11 | Great stuff!
Graphics objects and handles are in short supply so as a small improvement to the code I would always wrap in a try catch block with a finally that release the resources otherwise you run the risk of running out of memory/handles etc if the cleanup does not happen due to an earlier error.
__________________ Tim Titchmarsh
UK Iron Speed MVP
Dot Net Architect
+44 (0)1621 857758
http://www.dotnetarchitect.co.uk
timt@dotnetarchitect.co.uk |
| |