C# - Convert WPF Image.source to a System.Drawing.Bitmap - c#

I've found loads of people converting a BitmapSource to a Bitmap, but what about ImageSource to Bitmap? I am making an imaging program and I need to extract bitmaps from the image displayed in the Image element. Does anyone know how to do this?
EDIT 1:
This is a function for converting the BitmapImage to a Bitmap. Remember to set the 'unsafe' option in the compiler preferences.
public static System.Drawing.Bitmap BitmapSourceToBitmap(BitmapSource srs)
{
System.Drawing.Bitmap btm = null;
int width = srs.PixelWidth;
int height = srs.PixelHeight;
int stride = width * ((srs.Format.BitsPerPixel + 7) / 8);
byte[] bits = new byte[height * stride];
srs.CopyPixels(bits, stride, 0);
unsafe
{
fixed (byte* pB = bits)
{
IntPtr ptr = new IntPtr(pB);
btm = new System.Drawing.Bitmap(width, height, stride, System.Drawing.Imaging.PixelFormat.Format1bppIndexed, ptr);
}
}
return btm;
}
Next is now to get a BitmapImage:
RenderTargetBitmap targetBitmap = new RenderTargetBitmap(
(int)inkCanvas1.ActualWidth,
(int)inkCanvas1.ActualHeight,
96d, 96d,
PixelFormats.Default);
targetBitmap.Render(inkCanvas1);
MemoryStream mse = new MemoryStream();
System.Windows.Media.Imaging.BmpBitmapEncoder mem = new BmpBitmapEncoder();
mem.Frames.Add(BitmapFrame.Create(targetBitmap));
mem.Save(mse);
mse.Position = 0;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = mse;
bi.EndInit();
Next is to convert it:
Bitmap b = new Bitmap(BitmapSourceToBitmap(bi));

Actually you don't need to use unsafe code. There's an overload of CopyPixels that accepts an IntPtr:
public static System.Drawing.Bitmap BitmapSourceToBitmap2(BitmapSource srs)
{
int width = srs.PixelWidth;
int height = srs.PixelHeight;
int stride = width * ((srs.Format.BitsPerPixel + 7) / 8);
IntPtr ptr = IntPtr.Zero;
try
{
ptr = Marshal.AllocHGlobal(height * stride);
srs.CopyPixels(new Int32Rect(0, 0, width, height), ptr, height * stride, stride);
using (var btm = new System.Drawing.Bitmap(width, height, stride, System.Drawing.Imaging.PixelFormat.Format1bppIndexed, ptr))
{
// Clone the bitmap so that we can dispose it and
// release the unmanaged memory at ptr
return new System.Drawing.Bitmap(btm);
}
}
finally
{
if (ptr != IntPtr.Zero)
Marshal.FreeHGlobal(ptr);
}
}

That example worked for me:
public static Bitmap ConvertToBitmap(BitmapSource bitmapSource)
{
var width = bitmapSource.PixelWidth;
var height = bitmapSource.PixelHeight;
var stride = width * ((bitmapSource.Format.BitsPerPixel + 7) / 8);
var memoryBlockPointer = Marshal.AllocHGlobal(height * stride);
bitmapSource.CopyPixels(new Int32Rect(0, 0, width, height), memoryBlockPointer, height * stride, stride);
var bitmap = new Bitmap(width, height, stride, PixelFormat.Format32bppPArgb, memoryBlockPointer);
return bitmap;
}

Are your ImageSource not a BitmapSource? If your loading the images from files they should be.
Reply to your comment:
Sounds like they should be BitmapSource then, BitmapSource is a subtype of ImageSource. Cast the ImageSource to BitmapSource and follow one of those blogposts.

You don't need a BitmapSourceToBitmap method at all. Just do the following after creating your memory stream:
mem.Position = 0;
Bitmap b = new Bitmap(mem);

Related

How to create 1024x1024 RGB bitmap image of white?

It's embarrassing to ask this question but can't find an answer.
I tried this in vain.
Image resultImage = new Bitmap(image1.Width, image1.Height, PixelFormat.Format24bppRgb);
using (Graphics grp = Graphics.FromImage(resultImage))
{
grp.FillRectangle(
Brushes.White, 0, 0, image1.Width, image1.Height);
resultImage = new Bitmap(image1.Width, image1.Height, grp);
}
I basically want to fill a 1024x1024 RGB bitmap image with white in C#. How can I do that?
You almost had it:
private Bitmap DrawFilledRectangle(int x, int y)
{
Bitmap bmp = new Bitmap(x, y);
using (Graphics graph = Graphics.FromImage(bmp))
{
Rectangle ImageSize = new Rectangle(0,0,x,y);
graph.FillRectangle(Brushes.White, ImageSize);
}
return bmp;
}
You are assigning a new image to resultImage, thereby overwriting your previous attempt at creating a white image (which should succeed, by the way).
So just remove the line
resultImage = new Bitmap(image1.Width, image1.Height, grp);
Another approach,
Create a unit bitmap
var b = new Bitmap(1, 1);
b.SetPixel(0, 0, Color.White);
And scale it
var result = new Bitmap(b, 1024, 1024);
Graphics.Clear(Color)
Bitmap bmp = new Bitmap(1024, 1024);
using (Graphics g = Graphics.FromImage(bmp)){g.Clear(Color.White);}
Depending on your needs, a BitmapSource might suit. You can quickly fill a byte array with the 0xff (i.e. white) using Enumerable.Repeat().
int w = 1024;
int h = 1024;
byte[] pix = Enumerable.Repeat((byte)0xff, w * h * 4).ToArray();
SomeImage.Source = BitmapSource.Create(w, h, 96, 96, PixelFormats.Pbgra32, null, pix, w * 4);

C# convert stride/buffer/width/height to bitmap

I have an image width/height/stride and buffer.
How do I convert this information to a System.Drawing.Bitmap? Can I get the original image back if I have these 4 things?
There is a Bitmap constructor overload, which requires everything you have (plus PixelFormat):
public Bitmap(int width, int height, int stride, PixelFormat format, IntPtr scan0);
This might work (if args.Buffer is an array of blittable type, like byte for example):
Bitmap bitmap;
var gch = System.Runtime.InteropServices.GCHandle.Alloc(args.Buffer, GCHandleType.Pinned);
try
{
bitmap = new Bitmap(
args.Width, args.Height, args.Stride,
System.Drawing.Imaging.PixelFormat.Format24bppRgb,
gch.AddrOfPinnedObject());
}
finally
{
gch.Free();
}
Update:
Probably it's better to copy image bytes to newly created Bitmap manually, because it seems like that constructors doesn't do that, and if byte[] array of image data gets garbage collected all sorts of bad things can happen.
var bitmap = new Bitmap(args.Width, args.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
var data = bitmap.LockBits(
new Rectangle(0, 0, args.Width, args.Height),
System.Drawing.Imaging.ImageLockMode.WriteOnly,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);
if(data.Stride == args.Stride)
{
Marshal.Copy(args.Buffer, 0, data.Scan0, args.Stride * args.Height);
}
else
{
int arrayOffset = 0;
int imageOffset = 0;
for(int y = 0; y < args.Height; ++y)
{
Marshal.Copy(args.Buffer, arrayOffset, (IntPtr)(((long)data.Scan0) + imageOffset), data.Stride);
arrayOffset += args.Stride;
imageOffset += data.Stride;
}
}
bitmap.UnlockBits(data);
This should work if you have the buffer as byte[], a width and the height + the pixelformat (stride)
public Bitmap CreateBitmapFromRawDataBuffer(int width, int height, PixelFormat imagePixelFormat, byte[] buffer)
{
Size imageSize = new Size(width, height);
Bitmap bitmap = new Bitmap(imageSize.Width, imageSize.Height, imagePixelFormat);
Rectangle wholeBitmap = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
// Lock all bitmap's pixels.
BitmapData bitmapData = bitmap.LockBits(wholeBitmap, ImageLockMode.WriteOnly, imagePixelFormat);
// Copy the buffer into bitmapData.
System.Runtime.InteropServices.Marshal.Copy(buffer, 0, bitmapData.Scan0, buffer.Length);
// Unlock all bitmap's pixels.
bitmap.UnlockBits(bitmapData);
return bitmap;
}

Rendering out camera images to a WPF Image control

I have a uEye camera and I take snapshots of images at a 1000ms interval and I want to render them in a WPF Image Control like so
Bitmap MyBitmap;
// get geometry of uEye image buffer
int width = 0, height = 0, bitspp = 0, pitch = 0, bytespp = 0;
long imagesize = 0;
m_uEye.InquireImageMem(m_pCurMem, GetImageID(m_pCurMem), ref width, ref height, ref bitspp, ref pitch);
bytespp = (bitspp + 1) / 8;
imagesize = width * height * bytespp; // image size in bytes
// bulit a system bitmap
MyBitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb);
// fill the system bitmap with the image data from the uEye SDK buffer
BitmapData bd = MyBitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
m_uEye.CopyImageMem(m_pCurMem, GetImageID(m_pCurMem), bd.Scan0);
MyBitmap.UnlockBits(bd);
I am trying to put these bitmaps in to an Image control at the rate of 1 second. How can I get Bitmap to appear in the Image control and disposing them as soon as I'm done to leave minimal memory footprint to be a good little programmer :) ?
Here the way we do (for me it works at 200fps without loading CPU (about 5%)):
private WriteableBitmap PrepareForRendering(VideoBuffer videoBuffer) {
PixelFormat pixelFormat;
if (videoBuffer.pixelFormat == PixFrmt.rgb24) {
pixelFormat = PixelFormats.Rgb24;
} else if (videoBuffer.pixelFormat == PixFrmt.bgra32) {
pixelFormat = PixelFormats.Bgra32;
} else if (videoBuffer.pixelFormat == PixFrmt.bgr24) {
pixelFormat = PixelFormats.Bgr24;
} else {
throw new Exception("unsupported pixel format");
}
var bitmap = new WriteableBitmap(
videoBuffer.width, videoBuffer.height,
96, 96,
pixelFormat, null
);
_imgVIew.Source = bitmap;
return bitmap;
}
private void DrawFrame(WriteableBitmap bitmap, VideoBuffer videoBuffer, double averangeFps) {
VerifyAccess();
if (isPaused) {
return;
}
bitmap.Lock();
try {
using (var ptr = videoBuffer.Lock()) {
bitmap.WritePixels(
new Int32Rect(0, 0, videoBuffer.width, videoBuffer.height),
ptr.value, videoBuffer.size, videoBuffer.stride,
0, 0
);
}
} finally {
bitmap.Unlock();
}
fpsCaption.Text = averangeFps.ToString("F1");
}

create an empty BitmapSource in C#

What is the fastest (few lines of code and low resource usage) way to create an empty (0x0 px or 1x1 px and fully transparent) BitmapSource instance in c# that is used when nothing should be rendered.
Thanks to Arcutus hint I have this now (wich works fine):
var i = BitmapImage.Create(
2,
2,
96,
96,
PixelFormats.Indexed1,
new BitmapPalette(new List<Color> { Colors.Transparent }),
new byte[] { 0, 0, 0, 0 },
1);
If I make this image smaller I get an ArgumentException. I have no clue why I can't create a smaller image that 2x2px.
Use the Create method.
Example stolen from MSDN: :)
int width = 128;
int height = width;
int stride = width/8;
byte[] pixels = new byte[height*stride];
// Try creating a new image with a custom palette.
List<System.Windows.Media.Color> colors = new List<System.Windows.Media.Color>();
colors.Add(System.Windows.Media.Colors.Red);
colors.Add(System.Windows.Media.Colors.Blue);
colors.Add(System.Windows.Media.Colors.Green);
BitmapPalette myPalette = new BitmapPalette(colors);
// Creates a new empty image with the pre-defined palette
BitmapSource image = BitmapSource.Create(
width, height,
96, 96,
PixelFormats.Indexed1,
myPalette,
pixels,
stride);
The way to create such an image without allocating a big managed byte array is to use TransformedBitmap.
var bmptmp = BitmapSource.Create(1,1,96,96,PixelFormats.Bgr24,null,new byte[3]{0,0,0},3);
var imgcreated = new TransformedBitmap(bmptmp, new ScaleTransform(width, height));
The most minimal BitmapSource can be generated like this:
public static BitmapSource CreateEmptyBitmap()
{
return BitmapSource.Create(1, 1, 1, 1, PixelFormats.BlackWhite, null, new byte[] {0}, 1);
}
Another way is to create an instance of a BitmapImage class which is derived from BitmapSource:
BitmapSource emptySource = new BitmapImage();
Just take a look at this. It works for any Pixelformat
public static BitmapSource CreateEmtpyBitmapSource(int width, int height, PixelFormat pixelFormat)
{
PixelFormat pf = pixelFormat;
int rawStride = (width * pf.BitsPerPixel + 7) / 8;
var rawImage = new byte[rawStride * height];
var bitmap = BitmapSource.Create(width, height, 96, 96, pf, null, rawImage, rawStride);
return bitmap;
}

Using C# how can I resize a jpeg image?

Using C# how can I resize a jpeg image? A code sample would be great.
I'm using this:
public static void ResizeJpg(string path, int nWidth, int nHeight)
{
using (var result = new Bitmap(nWidth, nHeight))
{
using (var input = new Bitmap(path))
{
using (Graphics g = Graphics.FromImage((System.Drawing.Image)result))
{
g.DrawImage(input, 0, 0, nWidth, nHeight);
}
}
var ici = ImageCodecInfo.GetImageEncoders().FirstOrDefault(ie => ie.MimeType == "image/jpeg");
var eps = new EncoderParameters(1);
eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
result.Save(path, ici, eps);
}
}
Good free resize filter and example code.
http://code.google.com/p/zrlabs-yael/
private void MakeResizedImage(string fromFile, string toFile, int maxWidth, int maxHeight)
{
int width;
int height;
using (System.Drawing.Image image = System.Drawing.Image.FromFile(fromFile))
{
DetermineResizeRatio(maxWidth, maxHeight, image.Width, image.Height, out width, out height);
using (System.Drawing.Image thumbnailImage = image.GetThumbnailImage(width, height, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
{
if (image.Width < thumbnailImage.Width && image.Height < thumbnailImage.Height)
File.Copy(fromFile, toFile);
else
{
ImageCodecInfo ec = GetCodecInfo();
EncoderParameters parms = new EncoderParameters(1);
parms.Param[0] = new EncoderParameter(Encoder.Compression, 40);
ZRLabs.Yael.BasicFilters.ResizeFilter rf = new ZRLabs.Yael.BasicFilters.ResizeFilter();
//rf.KeepAspectRatio = true;
rf.Height = height;
rf.Width = width;
System.Drawing.Image img = rf.ExecuteFilter(System.Drawing.Image.FromFile(fromFile));
img.Save(toFile, ec, parms);
}
}
}
}
C# (or rather: the .NET framework) itself doesn't offer such capability, but it does offer you Bitmap from System.Drawing to easily access the raw pixel data of various picture formats. For the rest, see http://en.wikipedia.org/wiki/Image_scaling
Nice example.
public static Image ResizeImage(Image sourceImage, int maxWidth, int maxHeight)
{
// Determine which ratio is greater, the width or height, and use
// this to calculate the new width and height. Effectually constrains
// the proportions of the resized image to the proportions of the original.
double xRatio = (double)sourceImage.Width / maxWidth;
double yRatio = (double)sourceImage.Height / maxHeight;
double ratioToResizeImage = Math.Max(xRatio, yRatio);
int newWidth = (int)Math.Floor(sourceImage.Width / ratioToResizeImage);
int newHeight = (int)Math.Floor(sourceImage.Height / ratioToResizeImage);
// Create new image canvas -- use maxWidth and maxHeight in this function call if you wish
// to set the exact dimensions of the output image.
Bitmap newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format32bppArgb);
// Render the new image, using a graphic object
using (Graphics newGraphic = Graphics.FromImage(newImage))
{
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
newGraphic.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
// Set the background color to be transparent (can change this to any color)
newGraphic.Clear(Color.Transparent);
// Set the method of scaling to use -- HighQualityBicubic is said to have the best quality
newGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Apply the transformation onto the new graphic
Rectangle sourceDimensions = new Rectangle(0, 0, sourceImage.Width, sourceImage.Height);
Rectangle destinationDimensions = new Rectangle(0, 0, newWidth, newHeight);
newGraphic.DrawImage(sourceImage, destinationDimensions, sourceDimensions, GraphicsUnit.Pixel);
}
// Image has been modified by all the references to it's related graphic above. Return changes.
return newImage;
}
Source : http://mattmeisinger.com/resize-image-c-sharp
ImageMagick should be the best way. Easy and reliable.
using (var image = new MagickImage(imgfilebuf))
{
image.Resize(len, len);
image.Strip();
using MemoryStream ms = new MemoryStream();
image.Write(ms);
return ms.ToArray();
}

Categories