resizing and saving image

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.
Who is Participating?

Improve company productivity with a Business Account.Sign Up

gregoryyoungConnect With a Mentor Commented:

 ' 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 :)

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.

vbnewbie01Author Commented:
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.
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

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

vbnewbie01Author Commented:
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).

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

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

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...
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)
vbnewbie01Author Commented:
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.
vbnewbie01Author Commented:
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
any chance that we could close out the other question as well ?
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...
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."

does not work
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.