ArgumentException when loading image from byte array using JpegBitmapDecoder
I'm having some trouble reading JPEG files in my class. I need to load metadata and bitmap from a JPEG file. So far, I have this:
public void Load()
{
using (Stream imageStream = File.Open(this.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
BitmapDecoder decoder = new JpegBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
BitmapSource source = decoder.Frames[0];
// load metadata
this.metadata = source.Metadata as BitmapMetadata;
// prepare buffer
int octetsPerPixel = source.Format.BitsPerPixel / 8;
byte[] pixelBuffer = new byte[source.PixelWidth * source.PixelHeight * octetsPerPixel];
source.CopyPixels(pixelBuffer, source.PixelWidth * octetsPerPixel, 0);
Stream pixelStream = new MemoryStream(pixelBuffer);
// load bitmap
this.bitmap = new Bitmap(pixelStream); // throws ArgumentException
开发者_如何学运维 }
this.status = PhotoStatus.Loaded;
}
But the Bitmap constructor throws an ArgumentException when trying to create a Bitmap instance from a stream.
The documentation says:
System.ArgumentException
stream does not contain image data or is null.
-or-
stream contains a PNG image file with a single dimension greater than 65,535 pixels.
I'm not sure, what I did wrong. Can you please help me?
You're using the Bitmap
constructor which is usually used to load an image file in a known format - JPEG, PNG etc. Instead, you've just got a bunch of bytes, and you're not telling it anything about the format you want to use them in.
It's not clear why you want to use BitmapDecoder and BitmapSource at all - why aren't you just using:
Stream imageStream = File.Open(this.FilePath, FileMode.Open,
FileAccess.Read, FileShare.Read));
this.bitmap = new Bitmap(imageStream);
Note that you mustn't use a using
statement here - the Bitmap
"owns" the stream after you've called the constructor.
Aside from all of this, you seem to be trying to mix WPF and WinForms ideas of images, which I suspect is a generally bad idea :(
精彩评论