Reputation: 73
I want to draw a System.Windows.Media.Imaging.BitmapSource in a picture Box. in WPF application i do it with this :
image1.Source =BitmapSource.Create(....................);
but now I have a form. I import PresentationCore.dll in my form to have BitmapSource; but now how I can draw or show it On a PictureBox like this ? :
pictureBox1.Image=BitmapSource.Create(.....................);
Please help me. Thanks.
Upvotes: 4
Views: 5404
Reputation: 7450
This method has better performance (twice faster) and need lower memory as it doesn't copy data to MemoryStream
:
Bitmap GetBitmapFromSource(BitmapSource source) //, bool alphaTransparency
{
//convert image pixel format:
var bs32 = new FormatConvertedBitmap(); //inherits from BitmapSource
bs32.BeginInit();
bs32.Source = source;
bs32.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32;
bs32.EndInit();
//source = bs32;
//now convert it to Bitmap:
Bitmap bmp = new Bitmap(bs32.PixelWidth, bs32.PixelHeight, PixelFormat.Format32bppArgb);
BitmapData data = bmp.LockBits(new Rectangle(Point.Empty, bmp.Size), ImageLockMode.WriteOnly, bmp.PixelFormat);
bs32.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
bmp.UnlockBits(data);
return bmp;
}
Upvotes: 0
Reputation: 1532
why do you want/need to use wpf-specific things?
look at this snippet How to convert BitmapSource to Bitmap
Bitmap BitmapFromSource(BitmapSource bitmapsource)
{
Bitmap bitmap;
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapsource));
enc.Save(outStream);
bitmap = new Bitmap(outStream);
}
return bitmap;
}
Usage:
pictureBox1.Image = BitmapFromSource(yourBitmapSource);
If you want to open an image file...:
pictureBox1.Image = System.Drawing.Image.FromFile("C:\\image.jpg");
Upvotes: 4
Reputation: 23
Is it OK for you?
ImageSource imgSourceFromBitmap = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
Upvotes: 0