1

Now I am trying to get a Image Class from jpg Image. I already tried to use BitmapSource linked at here.

The error is not english, but the meaning is "the image header is broken. so, it is impossible to decode.". The other formats like gif, png, bmp has no problem. only jpg format faced on this problem.

< Sequence > An Zip Archive file(jpg file is in this file.) -> unzip library -> MemoryStream(jpg file) -> BitmapSource

imageSource.BeginInit();
imageSource.StreamSource = memoryStream;
imageSource.EndInit();

this code makes the error.

I think the reason is the memory stream has raw binary of jpg, and it is not Bitmap format. So, BitmapSource cannot recognize this memory stream data as a bitmap image.

How can I solve this problem? My goal is that Input : "ZIP File(in jpg)" -> Output : Image Class.

Thank you!

< My Code >

using (MemoryStream _reader = new MemoryStream())
{
    reader.WriteEntryTo(_reader);             // <- input jpg_data to _reader
    var bitmap = new BitmapImage();
    bitmap.BeginInit();
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.StreamSource = _reader;
    bitmap.EndInit();
    bitmap.Freeze();

    Image tmpImg = new Image();
    tmpImg.Source = bitmap;
}
Community
  • 1
  • 1
KONE Seion
  • 51
  • 1
  • 7

1 Answers1

3

Rewind the stream after writing. While apparently only JpegBitmapDecoder is affected by a source stream's Position, you should generally do this for all kinds of bitmap streams.

var bitmap = new BitmapImage();

using (var stream = new MemoryStream())
{
    reader.WriteEntryTo(stream);
    stream.Position = 0; // here

    bitmap.BeginInit();
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.StreamSource = stream;
    bitmap.EndInit();
    bitmap.Freeze();
}

var tmpImg = new Image { Source = bitmap };

And just in case you don't actually care about whether your Image's Source is a BitmapImage or a BitmapFrame, you may reduce your code to this:

BitmapSource bitmap;

using (var stream = new MemoryStream())
{
    reader.WriteEntryTo(stream);
    stream.Position = 0;
    bitmap = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}

var tmpImg = new Image { Source = bitmap };
Clemens
  • 123,504
  • 12
  • 155
  • 268