resizing and saving image

Posted on 2004-04-29
Last Modified: 2008-05-27
using (vb) i've successfully uploaded a photo into my image directory.

however, before i save it, i'd like to manipulate the width and height (while maintaining the aspect ratio).  

i've tried redefining the object's height and width (i.e. objImage.Width = 150), but the property is Read Only :(

2 questions:

1) after uploading, how would i go about resizing it in vb

2) since the image is currently being saved straight from the upload (i.e. inputPhotoUpload.PostedFile.SaveAs(strFilePathAndName) ....), how would i go about saving it after i muck around with it's properties?

thanks in advance.
Question by:vbnewbie01
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
  • 2
  • +4
LVL 21

Expert Comment

ID: 10947925
have alook at this url a very good site that explains how to resize images:

Another article in this site explains how to compress/decompress the jpeg, because
while resizing, the quality can change.  You can find this article at:

hope that this helps you.


Author Comment

ID: 10948032
hey there;

i've actually read that (and pretty much every other) article written on the subject, but it still doesn't address my question which is how to save the resized image.

i should have mentioned it above, but i've actually resized it, but it's outputted to a stream (i.e. displayed in browser window) and not saved to disk.  my question is how to save it to disk after resizing.

thanks anyway.

Author Comment

ID: 10948190
oh, and when i say i've resized it ... i mean, when i retrieve the uploaded image from the folder.

now, i can either pull it from the folder, resize it and save it back, or i can resize it before it's saved in the first place (which is what i want to do).

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 28

Expert Comment

ID: 10948414
you can use
System.Drawing.Bitmap.Save ( your_image_path )
it is menshioned in the first link tovvenki's posted

LVL 21

Expert Comment

ID: 10948432
in that case have a look at the following GetThumbnailImage function of the Image class in the System.Drawing namespace

Public Function GetThumbnailImage( _
   ByVal thumbWidth As Integer, _
   ByVal thumbHeight As Integer, _
   ByVal callback As Image.GetThumbnailImageAbort, _
   ByVal callbackData As IntPtr _
) As Image
The width, in pixels, of the requested thumbnail image.
The height, in pixels, of the requested thumbnail image.
A Image.GetThumbnailImageAbort delegate. In GDI+ version 1.0, the delegate is not used. Even so, you must create a delegate and pass a reference to that delegate in this parameter.
Must be IntPtr.Zero


Expert Comment

ID: 10948493
I know you need to use System.Drawing....  

Look at these examples below...

These show you how to resize an image from a file using the Bitmap object.  If you want to resize before you save it, the Bitmap has a constructor with accepts a Stream.  Then to save it, just call the Bitmap object's Save function

Another link...just for good measure...
LVL 37

Expert Comment

ID: 10954604
Image.Save(filename)  //you can also specify type etc

There are issues with using GetThumbNailImage() ... If the image has an embedded thumbnail (photoshop and digital cameras like to do this) it can lead to possibly unwanted results (as follows). Lets say I have a 800x600 image that I want to scale to 400x300... If it has an embedded thumbnail the GetThumbNailImage method will take the thumbnail (prob like 75x75) and scale it up to 400x300 as opposed to scaling the main image down. This saves processing power but it also leads to high amounts of loss in some situations. In other situations it leads to just plain funny results ... (remember it would use the embedded thumbnail instead of the real image)

Author Comment

ID: 10954939
gregory; here's the error i receive with that:

System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.

(and yes, permissions are set to the folder i'm writing to)

here's my code that works in displaying the image ... my question is how to save the resized image rather than have it displayed.

Sub ImageUpload(ByVal sender as system.object, ByVal e as system.EventArgs)
If Not inputPhotoUpload.PostedFile Is Nothing Then
'START Display Photo Information
'Read in the uploaded file into a Stream
Dim objStream as Stream = inputPhotoUpload.PostedFile.InputStream
Dim objImage as System.Drawing.Image = System.Drawing.Image.FromStream(objStream)
'assign photo height
dim OriginalPhotoHeight as integer
OriginalPhotoHeight = objImage.Height
'assign photo width
dim OriginalPhotoWidth as integer
OriginalPhotoWidth = objImage.Width

'List the properties of the Image
Dim strFileName as String = inputPhotoUpload.PostedFile.FileName
'Determine the file type
If objImage.RawFormat.Equals(ImageFormat.Gif) then lblImageProps.Text = "GIF"
If objImage.RawFormat.Equals(ImageFormat.Bmp) then lblImageProps.Text = "BMP"
If objImage.RawFormat.Equals(ImageFormat.Jpeg) then lblImageProps.Text = "JPEG"
If objImage.RawFormat.Equals(ImageFormat.Icon) then lblImageProps.Text = "Icon"
If objImage.RawFormat.Equals(ImageFormat.Tiff) then lblImageProps.Text = "TIFF"
'accessing the file format (i.e. jpeg) to the variable
dim strPhotoFormat as string
strPhotoFormat = "." & lblImageProps.Text

'display the photo information            
lblImageProps.Text &= "<br><b>Dimensions:</b> " & objImage.Width & " x " & objImage.Height & " pixels<br><b>Size:</b> " & objStream.Length & " bytes<br>" & "<b>Horizontal Resolution:</b> " & objImage.HorizontalResolution & " pixels per inch<br><b>Vertical Resolution:</b> " & objImage.VerticalResolution & " pixels per inch" & "<p>Filename: " & strFileName & "<p><img src=""" & strFileName & """>"


'START Resize the image


'START Save Photo
'Save the file if it has a filename and exists...
If inputPhotoUpload.PostedFile.FileName.Trim().Length > 0 AND inputPhotoUpload.PostedFile.ContentLength > 0 then
     Const strBaseDir as String = "C:\Inetpub\wwwroot\GMA\uploaded_images\"
     'the name and format of the uploaded file
     Dim strUploadedFile as String = Path.GetFileName(inputPhotoUpload.PostedFile.FileName)
     'save the uploaded photo on the server and name it whatever the user's name is, then add a Lg for the large photo
     dim strUploadedPhotoName as string = txtUsername.text

     inputPhotoUpload.PostedFile.SaveAs(strBaseDir & strUploadedPhotoName & strPhotoFormat)
     'File has been saved!
     lblResults.Text = "<hr><p>Your file, " & inputPhotoUpload.PostedFile.FileName & ", has been saved to the Web server!<br>" & "[<a href=""C:\Inetpub\wwwroot\GMA\uploaded_images\" & strUploadedFile & """> View File</a>]"
     'set the Filename to a session variable in case we need to repopulate the input control
     session("UploadedPhotoPath")= inputPhotoUpload.PostedFile.FileName

End If

End Sub


so, that's it.  i wrote this code which works perfectly to display the image information, then save the image.  but somewhere in between i need toresize it.  extra points if solved.
LVL 37

Accepted Solution

gregoryyoung earned 185 total points
ID: 10955006

 ' create New image and bitmap objects. Load the image file and put into a resized bitmap.
 dim g as System.Drawing.Image = System.Drawing.Image.FromFile(server.mappath(request("src"))) //use your from stream method.
 dim thisFormat = g.rawformat
 dim imgOutput as New Bitmap(g, cint(request("width")), cint(request("height")))

 ' Set the contenttype
 if thisformat.equals(system.drawing.imaging.imageformat.Gif) then
 end if

 ' send the resized image to the viewer, thisformat) ' output to the user

 ' tidy up

note that this is resizing without concern to aspect ratio ...

as for how to get the height and width to maintain aspect ratio. I answerred that question here :)


Author Comment

ID: 10955896
gregory; thanks for the response.

though you didn't answer the question directly, i really appreciate you getting me thinking in a different path.

before, i was trying to resize the image before it was saved.  what i did this time was saved the image first, then resized it AFTER it was saved to the folder.

thanks again everyone.

i'll post the solution below for anyone that's interested:


'call this subroutine from just before the END IF in my previous code post
'i.e. ResizeImage(strPathNameFormat, OriginalPhotoWidth, OriginalPhotoHeight) ... where strPathNameFormat is the path, name and format of the file you wish to resize, originalPhotoWidth and OriginalPhotoHeight are self explanatory.

Sub ResizeImage(ByVal imgPath As String, ByVal width As Integer, _
    ByVal height As Integer)
    ' select the format of the image to write according to the current extension
    Dim imgFormat As System.Drawing.imaging.ImageFormat = Imaging.ImageFormat.Jpeg
    ' open the image file
    Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(imgPath)

    dim NewWidth as integer
    NewWidth = 150
    dim NewHeight as integer
    NewHeight= (height * NewWidth)/width

    Dim bmp As New System.Drawing.Bitmap(NewWidth, NewHeight)
    Dim g As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(DirectCast(bmp, System.Drawing.Image))
   g.DrawImage(img, 0, 0, NewWidth, NewHeight)
    bmp.Save(imgPath, imgFormat)

End Sub
LVL 37

Expert Comment

ID: 10956373
any chance that we could close out the other question as well ?

Expert Comment

ID: 12052438
Hi Gregory,

You mention that you have to save the file first, before resizing it, and then savuing it.  Well I have modified your resize function to modify the image BEFORE saving it to the webserver.

Try this:

   Sub ResizeAndSaveImage(ByVal imgStream As System.IO.Stream, ByVal width As Integer, ByVal height As Integer, ByVal imgPath As String)

        ' select the format of the image to write according to the current extension
        Dim imgFormat As System.Drawing.imaging.ImageFormat = Imaging.ImageFormat.Jpeg

        ' open the image file
        'Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(imgPath)
        Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(imgStream)

        Dim NewWidth As Integer
        NewWidth = 150

        Dim NewHeight As Integer
        NewHeight = (height * NewWidth) / width

        Dim bmp As New System.Drawing.Bitmap(NewWidth, NewHeight)

        Dim g As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(DirectCast(bmp, System.Drawing.Image))

        g.DrawImage(img, 0, 0, NewWidth, NewHeight)


        bmp.Save(imgPath, imgFormat)


    End Sub

To call this function I used the following:

Call ResizeAndSaveImage(file.PostedFile.InputStream, 100, 200, Server.MapPath("ProductImages") & "\1_resized.jpg")

I hope this helps you for the future, I know its a little late coming but I just started using .NET and am just now needing to upload files...
LVL 37

Expert Comment

ID: 12055527
I at no point say that you need to save the image first ?

"dim g as System.Drawing.Image = System.Drawing.Image.FromFile(server.mappath(request("src"))) //use your from stream method."


Expert Comment

ID: 13833440
does not work

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on could not pull conte…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question