• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 491
  • Last Modified:

"generic error" Problem uploading image, code should work...

I am trying to get a form where users can upload an image and it will be resized and saved.  I have found several code examples online and this one seems very nice and self-contained, and works on the demo page.

However upon implmenting it in my project I get the error

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

(i commented out the try/catch in order to find which line has the error).

This error fires for lines

originalImg.save(Server.MapPath(upload_dir & upload_original & fileExt), originalImg.rawformat)


thumb.save(Server.MapPath(upload_dir & upload_thumb & fileExt), originalImg.rawformat)

I have permissions on the save folder set for everyone, and the folder is created in the same directory the ASPX file is stored in.

Anyone able to suss out the error here?

Thank you!

<%@ Page Trace="False" Language="vb" aspcompat="false" debug="true" validateRequest="false"%> 
<%@ Import Namespace=System.Drawing %>
<%@ Import Namespace=System.Drawing.Imaging %>
<%@ Import Namespace=System %>
<%@ Import Namespace=System.Web %>
<SCRIPT LANGUAGE="VBScript" runat="server">
const Lx = 200	' max width for thumbnails
const Ly = 240	' max height for thumbnails
const upload_dir = "/userImages/"	' directory to upload file
const upload_original = "sample"	' filename to save original as (suffix added by script)
const upload_thumb = "thumb"	' filename to save thumbnail as (suffix added by script)
const upload_max_size = 25	' max size of the upload (KB) note: this doesn't override any server upload limits
dim fileExt	' used to store the file extension (saves finding it mulitple times)
dim newWidth, newHeight as integer ' new width/height for the thumbnail
dim l2	' temp variable used when calculating new size
dim fileFld as HTTPPostedFile	' used to grab the file upload from the form
Dim originalimg As System.Drawing.Image	' used to hold the original image
dim msg	' display results
dim upload_ok as boolean	' did the upload work ?
randomize() ' used to help the cache-busting on the preview images
upload_ok = false
if lcase(Request.ServerVariables("REQUEST_METHOD"))="post" then
	fileFld = request.files(0)	' get the first file uploaded from the form (note:- you can use this to itterate through more than one image)
	if fileFld.ContentLength > upload_max_size * 1024 then
		msg = "Sorry, the image must be less than " & upload_max_size & "Kb"
	'	try
			originalImg = System.Drawing.Image.FromStream(fileFld.InputStream)
			' work out the width/height for the thumbnail. Preserve aspect ratio and honour max width/height
			' Note: if the original is smaller than the thumbnail size it will be scaled up
			If (originalImg.Width/Lx) > (originalImg.Width/Ly) Then
				L2 = originalImg.Width
				newWidth = Lx
				newHeight = originalImg.Height * (Lx / L2)
				if newHeight > Ly then
					newWidth = newWidth * (Ly / newHeight)
					newHeight = Ly
				end if
				L2 = originalImg.Height
				newHeight = Ly
				newWidth = originalImg.Width * (Ly / L2)
				if newWidth > Lx then
					newHeight = newHeight * (Lx / newWidth)
					newWidth = Lx
				end if
			End If
            Dim thumb As New Bitmap(newWidth, newHeight)
            'Create a graphics object           
            Dim gr_dest As Graphics = Graphics.FromImage(thumb)
			' just in case it's a transparent GIF force the bg to white 
			dim sb = new SolidBrush(System.Drawing.Color.White)
			gr_dest.FillRectangle(sb, 0, 0, thumb.Width, thumb.Height)
            'Re-draw the image to the specified height and width
			gr_dest.DrawImage(originalImg, 0, 0, thumb.Width, thumb.Height)
	'		try
				fileExt = System.IO.Path.GetExtension(fileFld.FileName).ToLower()
				originalImg.save(Server.MapPath(upload_dir & upload_original & fileExt), originalImg.rawformat)
				'thumb.save(Server.MapPath(upload_dir & upload_thumb & fileExt), originalImg.rawformat)
				response.write(upload_dir & upload_original & fileExt)
				msg = "Uploaded " & fileFld.FileName & " to " & Server.MapPath(upload_dir & upload_original & fileExt)
				upload_ok = true
	'		catch
	'			msg = "Sorry, there was a problem saving the image."
	'		end try
			' Housekeeping for the generated thumbnail
			if not thumb is nothing then
				thumb = nothing
			end if
	'	catch
	'		msg = "Sorry, that was not an image we could process."
	'	end try
	end if
	' House Keeping !
	if not originalImg is nothing then
		originalImg = nothing
	end if
end if
<title>ASP.NET File Upload and Resize Sample</title>
<META NAME="Description" CONTENT="ASP.NET File Upload and Resize Sample (Hybrid VB.NET)">
<META NAME="Keywords" CONTENT="ASP.NET, ASP, NET, VB, VBScript, Image, Upload, Resize, Thumbnail, Constrain, Filesize, File, Size, Free">
<META NAME="Copyright" CONTENT="Rufan-Redi Pty Ltd 2005">
<META NAME="Author" CONTENT="System developed by Jeremy at http://www.Rufan-Redi.com">
<p><b>Hybrid ASP.NET File Upload and Resize Sample (VB.NET)</b>
<br>Upload and resize a GIP/JPG/PNG images, ensuring filesizes are optimum.</p>
<form enctype="multipart/form-data" method="post" runat="server">
<tr><td>Select the file to upload:</td><td><input type="file" name="upload_file"></td></tr>
<tr><td colspan=2>Max upload size <%=upload_max_size%>Kb, gif/jpg/png only</td></tr>
<tr><td colspan=2><input type="submit" value="Upload"></td></tr>
if upload_ok then
<td valign=top><img src="<%=upload_dir & upload_original & fileExt & "?" & rnd()%>"></td>
<td valign=top><img src="<%=upload_dir & upload_thumb & fileExt & "?" & rnd()%>"></td>
end if

Open in new window

  • 4
1 Solution
Check if the path exists before trying to save. If you are missing a trailing slash it will throw an exception (And since the save would throw it would be a GDI+ error). Also check if the rawbitmap is actually filled and not null or length 0.
thearniecAuthor Commented:
I added to the code:
<%@ Import Namespace=System.IO %>

and then later

If Directory.Exists(upload_dir) Then
      response.write("directory valid")
      response.write("cannot find " & upload_dir & "<P>")
end if

It says it cannot find the directory.  

So if it is a path error, what would be causing it?  I've tried


It should be looking in the directory where the ASPX file is stored, and all paths relative to that, right?  Because I have a folder userImages in the same folder as my test ASPX.

Thakn you for your quick response!
thearniecAuthor Commented:
Additionally, I changed the upload directory to .\ which comes back as a valid directory.

And I have validated the image exists by inserting


and I get back

{Width=288, Height=288}.

But yet I still get the error on the .save methods...
thearniecAuthor Commented:
Sorry to keep adding but I'm testing more.

I added in some response.writes as shown in the code snippit below.  The path and filename appear correct.

With my upload directory as .\ which comes up directory valid, I get this output:  
directory valid{Width=288, Height=288}E:\MemNet2\CMS\warehouse\sample.jpg
directory valid

showing the file would be saved to my server's E drive and properly formatted in name and directory structure.  

And if I change it back to userImages

cannot find userImages\
{Width=288, Height=288}E:\MemNet2\CMS\warehouse\userImages\sample.jpg

directory valid

My first stest does not see just userImages but when I try the full path E:\...\userImages as shown above, it says directory valid.

And yet in both cases I get the same error on the save...

				fileExt = System.IO.Path.GetExtension(fileFld.FileName).ToLower()
				Response.Write(Server.MapPath(upload_dir & upload_original & fileExt) & "<P>")
				If Directory.Exists(Server.MapPath(upload_dir)) Then 
					response.write("directory valid<P>")  
					response.write("cannot find " & upload_dir & "<P>")
				end if
				'originalImg.save(Server.MapPath(upload_dir & upload_original & fileExt), originalImg.rawformat)
				'thumb.save(Server.MapPath(upload_dir & upload_thumb & fileExt), originalImg.rawformat)
				msg = "Uploaded " & fileFld.FileName & " to " & Server.MapPath(upload_dir & upload_original & fileExt)
				upload_ok = true
	'		catch
	'			msg = "Sorry, there was a problem saving the image."
	'		end try

Open in new window

thearniecAuthor Commented:
Got it!  IIS permissions error....

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now