Last post Jan 07, 2011 06:18 AM by Rouchie
Jan 06, 2011 12:07 PM|Rouchie|LINK
I have written a function that takes a System.Drawing.Image, resizes it, then returns it to the calling code.
Can anyone please explain why the code throws this error when the .Dispose methods are called at the end? When removed, the code works perfectly, but surely as part of good practice we should clear the resources after use?
Protected Function ResizeMyImage(ByVal ImageToResize As System.Drawing.Image, ByVal SizeChoice As ResizeOption, ByVal Pixels As Integer) As System.Drawing.Image
Dim workingBitmap As New Bitmap(ImageToResize)
Dim existingWidth As Integer = workingBitmap.Width
Dim existingHeight As Integer = workingBitmap.Height
Dim outputWidth As Integer
Dim outputHeight As Integer
' set new output dimensions
Select Case SizeChoice
outputWidth = Pixels
outputHeight = Convert.ToInt32(existingHeight / (existingWidth / Pixels))
outputHeight = Pixels
outputWidth = Convert.ToInt32(existingWidth / (existingHeight / Pixels))
' save output image
Dim outputBitmap As New Bitmap(outputWidth, outputHeight)
Dim ImageDrawer As Graphics = Graphics.FromImage(outputBitmap)
ImageDrawer.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias
ImageDrawer.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
ImageDrawer.DrawImage(workingBitmap, 0, 0, outputWidth, outputHeight)
Catch ex As Exception
used by doing this:
Dim uploadedImage As New System.Drawing.Bitmap(MyFileUpload.PostedFile.InputStream)
Dim imageToSave As System.Drawing.Image = ResizeMyImage(uploadedImage, e4LCMS.ResizeOption.Width, 750)
Dim savedir As String = Server.MapPath("~/somedir/")
imageToSave.Save(savedir & "_SomeFileName" & fileExtension) ' PARAMETER IS NOT VALID ERROR!
Jan 07, 2011 02:25 AMfirstname.lastname@example.org|LINK
The dispose method should be automatically called so there is no need to explicitly call the dispose method. You are disposing of the resource before you are finished using them
Jan 07, 2011 06:18 AM|Rouchie|LINK
I figured out what you were saying a few hours after posting, but before my post was approved. Yes, you are exactly write.
I incorrectly assumed that with most functions, ASP.NET would be using a working copy of the resource within the function, however, it appears all the subs share the image resource.
Therefore, you can dispose of the uploaded image, but cannot dispose of the final image until its usage has totally completed.
In my code the calling sub is responsible for deleting the final image:
Catch ex As Exception
' outputBitmap.Dispose() ' ERROR CAUSED HERE - let the calling sub Dispose when we've finished working with the image
I hope that explanation will help others who are facing this problem...!