Reputation: 1121
I have byte[]
that store some image of unknown size. I need to resize this bitmap into 160 x 160 and bind to Wpf window.
Should i convert byte[]
to Bitmap
, resize, make BitmapSource
from it and then use in wpf?
//result of this method binds to wpf
private static BitmapSource SetImage(byte[] dataBytes)
{
var picture = BitmapHelper.ByteToBitmap(dataBytes);
var resizedPicture = BitmapHelper.Resize(picture, 160, 160);
var bitmapSource = BitmapHelper.GetSourceFromBitmap(resizedPicture);
bitmapSource.Freeze();
return bitmapSource;
}
//BitmapHelper class:
public static Bitmap ByteToBitmap(byte[] byteArray)
{
using (var ms = new MemoryStream(byteArray))
{
var img = (Bitmap)Image.FromStream(ms);
return img;
}
}
internal static Bitmap Resize(Bitmap bitmap, int width, int height)
{
var newImage = new Bitmap(width, height);
using (var gr = Graphics.FromImage(newImage))
{
gr.SmoothingMode = SmoothingMode.HighQuality;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(bitmap, new Rectangle(0, 0, width, height));
}
return newImage;
}
internal static BitmapSource GetSourceFromBitmap(Bitmap source)
{
Contract.Requires(source != null);
var ip = source.GetHbitmap();
BitmapSource bs;
int result;
try
{
bs = Imaging.CreateBitmapSourceFromHBitmap(ip,
IntPtr.Zero, Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
}
finally
{
result = NativeMethods.DeleteObject(ip);
}
if (result == 0)
throw new InvalidOperationException("NativeMethods.DeleteObject returns 0 (operation failed)");
return bs;
}
internal static class NativeMethods
{
[DllImport("gdi32")]
static internal extern int DeleteObject(IntPtr o);
}
What is the fastest and common method for that case?
Upvotes: 0
Views: 1608
Reputation: 15197
I'd suggest you to use the DecodePixelWidth
and / or DecodePixelHeight
properties of the BitmapImage
class (which inherits from ImageSource
).
Take a look here:
BitmapSource GetImage(byte[] dataBytes)
{
using (MemoryStream stream = new MemoryStream(dataBytes))
{
BitmapImage bi = new BitmapImage();
bi.BeginInit();
// This is important: the image should be loaded on setting the StreamSource property, afterwards the stream will be closed
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.DecodePixelWidth = 160;
// Set this to 160 to get exactly 160x160 image
// Comment it out to retain original aspect ratio having the image width 160 and auto calculated image height
bi.DecodePixelHeight = 160;
bi.StreamSource = stream;
bi.EndInit();
return bi;
}
}
Upvotes: 1