Link to home
Start Free TrialLog in
Avatar of vbnewbie01
vbnewbie01

asked on

resizing and saving image

using asp.net (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.
Avatar of tovvenki
tovvenki

Hi,
have alook at this url a very good site that explains how to resize images:
http://www.aspalliance.com/chrisg/default.asp?article=21

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:
http://authors.aspalliance.com/chrisg/default.asp?article=157

hope that this helps you.

Regards,
Venki
Avatar of vbnewbie01

ASKER

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.
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).

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

B..M
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
were
thumbWidth
The width, in pixels, of the requested thumbnail image.
thumbHeight
The height, in pixels, of the requested thumbnail image.
callback
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.
callbackData
Must be IntPtr.Zero

I know you need to use System.Drawing....  

Look at these examples below...

http://www.devx.com/vb2themax/Tip/19660

http://www.plus.hr/skripte/asp.net/resize_image.html

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...

http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=0cd801c3b2a9%249064fb20%24a401280a%40phx.gbl&rnum=5&prev=/groups%3Fsourceid%3Dnavclient%26ie%3DUTF-8%26oe%3DUTF-8%26q%3Dresize%2Bsystem.drawing%2Bbitmap
Image.Save(filename)  //you can also specify type etc

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdrawingimageclasssavetopic1.asp

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 ... http://www.hutta.com/thumbs/tech.html (remember it would use the embedded thumbnail instead of the real image)
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 & """>"

objImage.Dispose()


'----------------------------------------------------------
'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
     inputPhotoUpload.Value=session("UploadedPhotoPath")

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.
ASKER CERTIFIED SOLUTION
Avatar of gregoryyoung
gregoryyoung
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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)
   
   img.Dispose()
   
    bmp.Save(imgPath, imgFormat)
   
    bmp.Dispose()

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)

        img.Dispose()

        bmp.Save(imgPath, imgFormat)

        bmp.Dispose()

    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