WPF - BitmapImage

Converting Bitmap to BitmapImage.
code
Bitmap bmp = GetBitmap(); // Get bitmap from somewhere
BitmapImage bi = new BitmapImage();
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
bi.BeginInit();
ms.Seek(0, SeekOrigin.Begin);

bi.CacheOption = BitmapCacheOption.OnLoad;
bi.StreamSource = ms;
bi.DecodePixelHeight = 30;
bi.DecodePixelWidth = 50;
bi.EndInit();
bi.StreamSource.Dispose();

// Dispose and free resources.
bmp.Dispose();
bmp = null;
ms.Dispose();
ms = null;


Converting Byte[] to BitmapImage.
code
Byte[] imageByte = GetImageByte(); // Get byte[] from somewhere
MemoryStream ms = new MemoryStream(imageByte);
ms.Seek(0, SeekOrigin.Begin);

BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.StreamSource = ms;
bi.EndInit();
bi.Freeze();

ms.Dispose();
ms = null;


Saving BitmapImage as jpeg file.
code
BitmapImage bi = GetBitmapImage() // Get bitmapimage from somewhere
using (FileStream stream = new FileStream("img.jpeg", FileMode.Create))
{
    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bi));
    encoder.Save(stream);
    stream.Close();
}


Converting BitmapImage to Byte[].
code
BitmapImage bi = GetBitmapImage() // Get bitmapimage from somewhere
Stream stream = bi.StreamSource;
Byte[] imageByte = null;
using (BinaryReader reader = new BinaryReader(stream))
{
    imageByte = reader.ReadBytes((Int32)stream.Length);
}


Converting BitmapImage to Bitmap. (Seldom use)
code
BitmapImage bi = GetBitmapImage(); // Get bitmapimage from somewhere
MemoryStream ms = newMemoryStream();
BitmapEncoder encoder = new BitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bi));
encoder.Save(ms);
Bitmap bmp = new Bitmap(ms);

3 comments:

jack said...

your example is very useful. Thank you

Anonymous said...

in the "Converting Byte[] to BitmapImage" example how does the BitmapImage know what dimension the image is, i.e. how can it possibly infer the width and height from the byte[].length property? let alone the pixel format, stride etc??

Hamitai said...

From "Converting Byte[] to BitmapImage" example, there is no assignment of width or height with the byte[].length property. BitmapImage will known the width and height once you converted it from byte[].

Post a Comment

top