'Convert .Net Bitmap() to MagickImage
An upgrade from ImageMagick 7.17 to 7.22.2.1 NuGet results in the following error on the constructor of a MagickImage. I can't put my finger on the replacement methods. Help me locate the documentation. Thank you,
Argument 1: cannot convert from 'System.Drawing.Bitmap' to 'byte[]'
Code:
var bitmap = new Bitmap(somesource);
var m = new MagickImage(bitmap);
Solution 1:[1]
Bitmap reader was moved to Magic.NET.SystemDrawing.
var m = new MagickFactory();
MagickImage image = new MagickImage(m.Image.Create(objImage));
Solution 2:[2]
I've only just started playing with this, so this may not be great code, but it has worked for me so far.
public static Bitmap ToBitmap(this IMagickImage mimg, MagickFormat fmt = MagickFormat.Png24)
{
Bitmap bmp = null;
using (MemoryStream ms = new MemoryStream())
{
mimg.Write(ms, fmt);
ms.Position = 0;
bmp = (Bitmap)Bitmap.FromStream(ms);
}
return bmp;
}
public static IMagickImage ToMagickImage(this Bitmap bmp)
{
IMagickImage img = null;
MagickFactory f = new MagickFactory();
using (MemoryStream ms = new MemoryStream())
{
bmp.Save(ms, ImageFormat.Bmp);
ms.Position = 0;
img = new MagickImage(f.Image.Create(ms));
}
return img;
}
Some ImageMagick operations seem to require a different format when writing to the stream, so you may need to play with the fmt parameter.
Solution 3:[3]
I ended up using both answers to use my bitmaps with MagickImageCollection().
using var collection = new MagickImageCollection();
for(var frame = 0; frame < _animation.Length; frame++) {
Bitmap bitmap = _animation[frame];
Bitmap canvas = new Bitmap(bitmap.Width, bitmap.Height);
MagickFactory magickFactory = new MagickFactory();
using MemoryStream memoryStream = new MemoryStream();
using Graphics graphics = Graphics.FromImage(canvas);
graphics.FillRectangle(Brushes.Transparent, 0, 0, bitmap.Width, bitmap.Height);
graphics.DrawImage(bitmap, new Point(0, 0));
canvas.Save(memoryStream, ImageFormat.Png);
canvas.Dispose();
collection.Add(new MagickImage(magickFactory.Image.Create((Bitmap)Image.FromStream(memoryStream))));
collection[frame].AnimationDelay = 100;
memoryStream.Close();
}
collection.Quantize(new QuantizeSettings { Colors = 256 });
collection.Write(dialog.FileName);
collection.Dispose();
I should note that I am using Magick.NET.SystemDrawing v4.0.19 and Magick.NET-Q16-AnyCPU v11.0.0 in this project. I hope this helps for future readers.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hintz |
| Solution 2 | |
| Solution 3 | Daerik |
