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

Posted on 2008-09-30
Last Modified: 2013-12-25
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 & upload_original & fileExt), originalImg.rawformat)

and & 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() & upload_original & fileExt), originalImg.rawformat)

				' & 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">



<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

Question by:thearniec
  • 4

Expert Comment

ID: 22606496
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.

Author Comment

ID: 22606604
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!

Author Comment

ID: 22606663
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...

Author Comment

ID: 22606752
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

				' & upload_original & fileExt), originalImg.rawformat)

				' & 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


Accepted Solution

thearniec earned 0 total points
ID: 22606829
Got it!  IIS permissions error....

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

"In order to have an organized way for empathy mapping, we rely on a psychological model and trying to model it in a simple way, so we will split the board to three section for each persona and a scenario and try to see what those personas would Do,…
Developer portfolios can be a bit of an enigma—how do you present yourself to employers without burying them in lines of code?  A modern portfolio is more than just work samples, it’s also a statement of how you work.
This tutorial demonstrates how to identify and create boundary or building outlines in Google Maps. In this example, I outline the boundaries of an enclosed skatepark within a community park.  Login to your Google Account, then  Google for "Google M…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

932 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

12 Experts available now in Live!

Get 1:1 Help Now