Solved

resizing and saving image

Posted on 2004-04-29
14
9,774 Views
Last Modified: 2008-05-27
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.
0
Comment
Question by:vbnewbie01
  • 4
  • 4
  • 2
  • +4
14 Comments
 
LVL 21

Expert Comment

by:tovvenki
ID: 10947925
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
0
 
LVL 1

Author Comment

by:vbnewbie01
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.
0
 
LVL 1

Author Comment

by:vbnewbie01
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).

cheers.
0
 
LVL 28

Expert Comment

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

B..M
0
 
LVL 21

Expert Comment

by:tovvenki
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
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

0
 
LVL 1

Expert Comment

by:warmach
ID: 10948493
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
0
 
LVL 37

Expert Comment

by:gregoryyoung
ID: 10954604
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)
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 1

Author Comment

by:vbnewbie01
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 & """>"

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.
0
 
LVL 37

Accepted Solution

by:
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
       response.contenttype="image/gif"
 else
       response.contenttype="image/jpeg"
 end if



 ' send the resized image to the viewer
 imgOutput.save(FilenameYouWant, thisformat) ' output to the user

 ' tidy up
 g.dispose()
 imgOutput.dispose()

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 :) http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/ASP.NET/Q_20966308.html

0
 
LVL 1

Author Comment

by:vbnewbie01
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)
   
   img.Dispose()
   
    bmp.Save(imgPath, imgFormat)
   
    bmp.Dispose()

End Sub
0
 
LVL 37

Expert Comment

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

Expert Comment

by:michaelsowa
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)

        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...
0
 
LVL 37

Expert Comment

by:gregoryyoung
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."

0
 

Expert Comment

by:momentuminfotech
ID: 13833440
does not work
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

706 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now