views:

276

answers:

1

I have a FileUpload control. I am trying to save the file that is uploaded (an image) and also save several thumbnail copies of the file.

When I try something like this:

System.Drawing.Image imgOriginal = System.Drawing.Image.FromStream(PhotoUpload.PostedFile.InputStream);

I get an "System.ArgumentException: Parameter is not valid."

I also tried using the PhotoUpload.FileBytes to create the image from the file bytes instead of the InputStream, but the same error occurs.

The uploaded file is a jpg. I know it's a valid jpg since it saves the original ok.

Edit: This code actually does work. The Parameter is not valid was due to the PhotoUpload.PostedFile.InputStream being empty... which seems to be an entirely different issue. It looks like after I save the original the fileupload stream goes away.

Edit: Found out that the InputStream of a FileUpload can only be read/consumed one time and then it is gone.

To get around that I saved the fileupload filebytes into a byte array and used the byte array to create copies of the image.

Code:

// Copy the FileBytes into a byte array
byte[] imageData = PhotoUpload.FileBytes;

// Create a stream from the byte array if you want to save it somewhere:
System.IO.Stream myStream = new System.IO.MemoryStream(imageData);

// Or create an image from the stream as many times as needed:
System.Drawing.Image imgOriginal = System.Drawing.Image.FromStream(myStream);
+1  A: 

Have a look at this link

ASP Net - How to pass a postedfile to a system.drawing.image

Here's my function call:

uploadAndSizeImage(System.Drawing.Image.FromStream (uploadedFileMD.PostedFile.InputStream))

I'm getting this error:

Exception Details: System.ArgumentException: Invalid parameter used.

Google isn't turning up much though I did find a reference to it possibly being caused by the stream reader being at the end of the stream and me needing to reset it to position one. But that was kind of vague and not really sure if it applies here.

Does this help?

EDIT:

Also, have you tried manually reading the file using something like

System.IO.FileStream fs = System.IO.File.OpenRead(@"Image.JPG");
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);

System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
System.Drawing.Image image = Image.FromStream(ms);

Or saving a temp copy from the FileUpload and loading the image from file?

astander
Thanks, this did help, though my issue now is not the conversion. I found out that my FileUpload content is gone when I make this call... somewhere before I make this call I save the file upload and after that it is gone... not sure if that makes any sense. But now I need to figure out how to keep the fileupload content.
metanaito