WPF image to form picture picturebox [duplicate] - c#

I'm tying together two libraries. One only gives output of type System.Windows.Media.Imaging.BitmapSource, the other only accepts input of type System.Drawing.Image.
How can this conversion be performed?

private System.Drawing.Bitmap BitmapFromSource(BitmapSource bitmapsource)
{
System.Drawing.Bitmap bitmap;
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapsource));
enc.Save(outStream);
bitmap = new System.Drawing.Bitmap(outStream);
}
return bitmap;
}

This is an alternate technique that does the same thing. The accepted answer works, but I ran into problems with images that had alpha channels (even after switching to PngBitmapEncoder). This technique may also be faster since it just does a raw copy of pixels after converting to compatible pixel format.
public Bitmap BitmapFromSource(System.Windows.Media.Imaging.BitmapSource bitmapsource)
{
//convert image format
var src = new System.Windows.Media.Imaging.FormatConvertedBitmap();
src.BeginInit();
src.Source = bitmapsource;
src.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32;
src.EndInit();
//copy to bitmap
Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
bitmap.UnlockBits(data);
return bitmap;
}

Related

How to create a Image or Mat instance from a YUV_420_888 byte array in EmguCV?

The problem:
I receive a YUV_420_888 image from an android device as a byte buffer (simply concatenated the image plane buffers). I know the dimension of the image and I need to display it onto my GUI.
What I have so far:
At the moment I can use only the grayscale Y-plane with the following function:
private BitmapImage GetImageFromBuffer(byte[] imgBuffer)
{
Image<Gray, byte> emguImg = new Image<Gray, byte>(1280, 720);
emguImg.Bytes = imgBuffer;
var img = new BitmapImage();
using (MemoryStream ms = new MemoryStream(emguImg.ToJpegData()))
{
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
img.StreamSource = ms;
img.EndInit();
}
return img;
}
I also have tested a similar code, using Image.ToBitmap() function and copying the intermediate Bitmap to the memory stream, which serves as source for the BitmapImage.
Anyway, I would like to create a BitmapImage of BitmapSource (or any type I can use to display on the GUI) from the incoming byte[].
As far as I could read up on it, I have to create a Mat instance from the byte array, convert it to RGB and then save it to a diplay-able format.
The following code seems to do the trick:
private BitmapImage GetImageFromBuffer(byte[] imgBuffer)
{
unsafe
{
fixed (byte* p = imgBuffer)
{
IntPtr ptr = (IntPtr)p;
Mat yuvMat = new Mat(1080, 1280, Emgu.CV.CvEnum.DepthType.Cv8U, 1, ptr, 1280);
Mat rgbMat = new Mat();
CvInvoke.CvtColor(yuvMat, rgbMat, Emgu.CV.CvEnum.ColorConversion.Yuv420Sp2Rgb);
var img = new BitmapImage();
using (MemoryStream ms = new MemoryStream())
{
img.BeginInit();
rgbMat.Bitmap.Save(ms, ImageFormat.Bmp);
img.CacheOption = BitmapCacheOption.OnLoad;
img.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
img.StreamSource = ms;
img.EndInit();
}
return img;
}
}
}
Maybe someone can confirm, if this is the way to go or comment suggestions for improvements.

Convert WriteableBitmap to BitmapImage using BmpBitmapEncoder WPF

I have a problem with Convert WriteableBitmap to BitmapImage using BmpBitmapEncoder.
this is my method:
public BitmapImage ConvertWriteableBitmapToBitmapImage(WriteableBitmap wbm)
{
bmp = new BitmapImage();
using (MemoryStream stream = new MemoryStream())
{
/*PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(wbm));
encoder.Save(stream);*/
BmpBitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(wbm));
encoder.Save(stream);
bmp.BeginInit();
bmp.UriSource = new Uri(MyImage.Source.ToString());
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.CreateOptions = BitmapCreateOptions.IgnoreImageCache | BitmapCreateOptions.PreservePixelFormat;
bmp.StreamSource = stream;
bmp.EndInit();
bmp.Freeze();
}
return bmp;
}
I'm using BmpBitmapEncoder because this is only way to Save without change size of Image(*.bmp). I want to Save Image with changed table of pixels and the specified format pixel (Bgr24). Using BmpBitmapEncoder forces to set bmp.UriSource and this is a problem. WriteableBitmap doesn't have this Property. Moreover, when I comment line //bmp.UriSource shows me an exception: "System.ArgumentNullException" in bmp.EndInit().
When I change my Method to this:
public BitmapImage ConvertWriteableBitmapToBitmapImage(WriteableBitmap wbm)
{
bmp = new BitmapImage();
using (MemoryStream stream = new MemoryStream())
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(wbm));
encoder.Save(stream);
/*BmpBitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(wbm));
encoder.Save(stream);*/
bmp.BeginInit();
//bmp.UriSource = new Uri(MyImage.Source.ToString());
bmp.CacheOption = BitmapCacheOption.OnLoad;
//bmp.CreateOptions = BitmapCreateOptions.IgnoreImageCache | BitmapCreateOptions.PreservePixelFormat;
bmp.StreamSource = stream;
bmp.EndInit();
bmp.Freeze();
}
return bmp;
}
everything works fine but the result is the Image increase size and change pixel format to Bgr32 and this is not the result, what I expect. My method which Save Image is fine because I tested it on unchanged pixels and the result is good - Image don't change format and size. Plz help me with this.
For changing pixel formats WPF has the FormatConvertedBitmap class, which is a BitmapSource:
WriteableBitmap wbm;
...
var bm = new FormatConvertedBitmap(wbm, PixelFormats.Bgr24, null, 0);
It is not a BitmapImage, but you do not really need that anywhere. All WPF methods and properties (e.g. Image.Source) use either ImageSource or the derived BitmapSource as their type. There is no API that explicitly needs a BitmapImage, so conversion to BitmapImage is never necessary.
I resolve this problem. This is a code which Convert WriteableBitmap to BitmapImage using BmpBitmapEncoder. Using this method ensure us, that our Image while saving stay unchanged. Unchanged I mean - size don't increase and Format Pixel stay on Bgr24.
public BitmapImage ConvertWriteableBitmapToBitmapImage(WriteableBitmap wbm)
{
bmp = new BitmapImage();
using (MemoryStream stream = new MemoryStream())
{
BmpBitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(wbm));
encoder.Save(stream);
bmp.BeginInit();
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
bmp.StreamSource = new MemoryStream(stream.ToArray()); //stream;
bmp.EndInit();
bmp.Freeze();
}
return bmp;
}

Converting from Bitmap to JPEG and retaining original Bitmap resolution

I am using the below code to transform a bitmap to jpeg. The bitmap is being passed through at 300 dpi (horizontal/vertical resolution) but the CreateBitmapSourcefromHBitmap method always changes the subsequent jpeg to be saved at 96dpi.
Is there any way to set the source to retain the original 300dpi? The dpiX and dpiY values are read only.
Thanks in advance.
public static MemoryStream GetJpgMemoryStream(Bitmap bitMap, int jpgQuality)
{
IntPtr hBitmap = bitMap.GetHbitmap();
try
{
BitmapSource source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
var jpegBitmapEncoder = new JpegBitmapEncoder();
jpegBitmapEncoder.QualityLevel = jpgQuality;
jpegBitmapEncoder.Frames.Add(BitmapFrame.Create(source));
var jpegStream = new MemoryStream();
jpegBitmapEncoder.Save(jpegStream);
jpegStream.Flush();
return jpegStream;
}
}
The MSDN Forum has a discussion that's similar to your problem. The recommended answer is to not use the Interop, instead use a WriteableBitmap as the BitmapSource for the JPEG.
You have to change the method used for generating the BitmapSource. You can use the method stated in fast converting Bitmap to BitmapSource wpf for generating BitmapSource. Here is the updated code.
BitmapData data = bitMap.LockBits(
new System.Drawing.Rectangle(0,0,bitMap.Width,bitMap.Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly,
bitMap.PixelFormat);
BitmapSource source = BitmapSource.Create(bitMap.Width, bitMap.Height,
bitMap.HorizontalResolution, bitMap.VerticalResolution,
System.Windows.Media.PixelFormats.Bgr24, null,
data.Scan0, data.Stride*bitMap.Height, data.Stride);
bitMap.UnlockBits(data);
var jpegBitmapEncoder = new JpegBitmapEncoder();
jpegBitmapEncoder.QualityLevel = jpgQuality;
jpegBitmapEncoder.Frames.Add(BitmapFrame.Create(source));
var jpegStream = new MemoryStream();
jpegBitmapEncoder.Save(jpegStream);

How to crop a tiff image in asp.net

I was looking for a routine by which I can crop tiff image and I got it but it gives many error. Here is the routine:
Bitmap comments = null;
string input = "somepath";
// Open a Stream and decode a TIFF image
using (Stream imageStreamSource = new FileStream(input, FileMode.Open, FileAccess.Read, FileShare.Read))
{
TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];
using (Bitmap b = BitmapFromSource(bitmapSource))
{
Rectangle cropRect = new Rectangle(169, 1092, 567, 200);
comments = new Bitmap(cropRect.Width, cropRect.Height);
//first cropping
using (Graphics g = Graphics.FromImage(comments))
{
g.DrawImage(b, new Rectangle(0, 0, comments.Width, comments.Height),
cropRect,
GraphicsUnit.Pixel);
}
}
}
When I try to compile it, I get an error. I tried adding references to many assemblies searching google but couldn't resolve it. I got this code from this url:
http://snipplr.com/view/63053/
I am looking for advice.
TiffBitmapDecoder class is from Presentation.Core in another words it is from WPF.
BitmapFromSource isn't method of any .net framework class. You can convert BitmapSource to Bitmap using this code.
private Bitmap BitmapFromSource(BitmapSource bitmapsource)
{
Bitmap bitmap;
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapsource));
encoder.Save(outStream);
bitmap = new Bitmap(outStream);
}
return bitmap;
}

How do I convert DrawingVisual to a Bitmap?

Using Visual C# 2010, I'm trying to write an .avi file from frames received from a Windows Kinect. The frames can be saved easily enough as .png files with the use of a BitmapEncoder and PngBitmapEncoder (saving to a stream) but I can't add these images at my discretion to a VideoStream provided here:
http://www.codeproject.com/Articles/7388/A-Simple-C-Wrapper-for-the-AviFile-Library
because I need to be able to convert either a RenderTargetBitmap or a DrawingVisual to a System.Drawing.Bitmap.
I've found example codes that do similar things but they all seem to want to instantiate the Image class which Visual Studio tells me is abstract and can't be instantiated.
I'm going round in circles and not getting anywhere.
I just want to do something like this:
...
renderBitmap.Render(dv);
Bitmap bmp=new Bitmap(dv);
VideoStream aviStream=aviManager.AddVideoStream(true,60,bmp);
...
But Bitmap has no useful constructors to get me from dv (DrawingVisual) to bmp. :(
Those 3 lines come from this snippet:
var renderBitmap=new RenderTargetBitmap(colorWidth,colorHeight,96.0,96.0,PixelFormats.Pbgra32);
DrawingVisual dv=new DrawingVisual();
using(DrawingContext dc=dv.RenderOpen())
{
VisualBrush backdropBrush=new VisualBrush(Backdrop);
dc.DrawRectangle(backdropBrush,null,new Rect(0,0,colorWidth,colorHeight));
VisualBrush colorBrush=new VisualBrush(MaskedColor);
dc.DrawRectangle(colorBrush,null,new Rect(0,0,colorWidth,colorHeight));
VisualBrush watermarkBrush=new VisualBrush(Watermark);
dc.DrawRectangle(watermarkBrush,null,new Rect(colorWidth-96,colorHeight-80,64,48));
}
renderBitmap.Render(dv);
Bitmap bmp=new Bitmap(dv);
VideoStream aviStream=aviManager.AddVideoStream(true,60,bmp);
The result of using RenderTargetBitMap is a WPF BitMapSource it doesn't convert the Visual itself to a BitmapSource, it contains the result of the conversion as a BitmapSource. In order to convert a BitmapSource to a System.Drawing.Bitmap try using a modified version of the code from this MSDN Forum Post.
renderBitmap.Render(dv);
BitmapSource bmp = renderBitmap;
using(MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bmp));
enc.Save(outStream);
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);
VideoStream aviStream=aviManager.AddVideoStream(true,60,bitmap);
}
Created a Method to return your Bitmap
renderBitmap.Render(dv);
BitmapSource bmp =renderBitmap;
VideoStream aviStream = aviManager.AddVideoStream(true, 60, ConvertToBitmap(bmp));
private System.Drawing.Bitmap ConvertToBitmap(BitmapSource target)
{
System.Drawing.Bitmap bitmap;
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(target));
enc.Save(outStream);
bitmap = new System.Drawing.Bitmap(outStream);
}
return bitmap;
}
private BitmapSource ToBitmapSource(Visual visual, Brush transparentBackground)
{
var bounds = VisualTreeHelper.GetDescendantBounds(visual);
var scale = VisualTreeHelper.GetDpi(visual);
var bitmapSource = new RenderTargetBitmap(
(int)(bounds.Width * scale.DpiScaleX),
(int)(bounds.Height * scale.DpiScaleY),
scale.PixelsPerInchX,
scale.PixelsPerInchY,
PixelFormats.Pbgra32);
var drawingVisual = new DrawingVisual();
using (var drawingContext = drawingVisual.RenderOpen())
{
drawingContext.DrawRectangle(transparentBackground, null, new Rect(bounds.Size));
drawingContext.DrawRectangle(new VisualBrush(visual), null, new Rect(bounds.Size));
}
bitmapSource.Render(drawingVisual);
return bitmapSource;
}
private System.Drawing.Bitmap BitmapFromSource(BitmapSource bitmapsource)
{
System.Drawing.Bitmap bitmap;
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapsource));
enc.Save(outStream);
bitmap = new System.Drawing.Bitmap(outStream);
}
return bitmap;
}

Categories