简体   繁体   中英

FileStream to Bitmap - Parameter is not valid

I have read the posts on this subject but none of them explains it to me clearly enough to be able to fix the problem.

I am trying to upload a file from a local directory to the server.

Here is my code:

string fullPath = Path.Combine(
    AppDomain.CurrentDomain.BaseDirectory + @"Images\Readings", PhotoFileName);

Stream s = System.IO.File.OpenRead(fileUpload);

byte[] buffer = new byte[s.Length];

s.Read(buffer, 0, Convert.ToInt32(s.Length));

using (FileStream fs = new FileStream(fullPath, FileMode.Create))
{
    fs.Write(buffer, 0, Convert.ToInt32(fs.Length));

    Bitmap bmp = new Bitmap((Stream)fs);

    bmp.Save(fs, ImageFormat.Jpeg);
}

I keep on getting an Argument Exception: "Parameter is not valid" on line:

Bitmap bmp = new Bitmap((Stream)fs);

Can anyone explain this to me please

There are at least two problems, probably three. First, your copying code is broken:

byte[] buffer = new byte[s.Length];
s.Read(buffer, 0, Convert.ToInt32(s.Length));

You've assumed that this will read all of the data in a single Read call, and ignored the return value for Read . Generally, you'd need to loop round, reading data and writing it (the amount you've just read) to the output stream, until you read the end. However, as of .NET 4, Stream.CopyTo makes this much simpler.

Next is how you're creating the bitmap:

using (FileStream fs = new FileStream(fullPath, FileMode.Create))
{
    fs.Write(buffer, 0, Convert.ToInt32(fs.Length));
    Bitmap bmp = new Bitmap((Stream)fs);    
    bmp.Save(fs, ImageFormat.Jpeg);
}

You're trying to read from the stream when you've just written to it - but without "rewinding"... so there's no more data left to read.

Finally, I would strongly advise against using Bitmap.Save to write to the same stream that you're loading the bitmap from. Bitmap will keep a stream open, and read from it when it needs to - if you're trying to write to it at the same time, that could be very confusing.

It's not clear why you're using Bitmap at all, to be honest - if you're just trying to save the file that was uploaded, without any changes, just use:

using (Stream input = File.OpenRead(fileUpload),
              output = File.Create(fullPath))
{
    input.CopyTo(output);
}

This is assuming that fileUpload really is an appropriate filename - it's not clear why you haven't just written the file to the place you want to write it to straight away, to be honest. Or use File.Copy to copy the file. The above code should work with any stream, so you can change it to save the stream straight from the request...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM