I'm converting byte[] to bitmap using this function:
public static Bitmap ArrayToBitmap(
byte[] bytes, int width, int height, PixelFormat pixelFormat)
{
var image = new Bitmap(width, height, pixelFormat);
var imageData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
ImageLockMode.ReadWrite, pixelFormat);
try
{
Marshal.Copy(bytes, 0, imageData.Scan0, bytes.Length);
}
finally
{
image.UnlockBits(imageData);
}
return image;
}
this works great. If I convert the result back to byte[] and output it as ByteArrayContent I see the resulting image in the browser. My source file is a PNG and for pixelFormat parameter I can use either Format16bppArgb1555 or Format32bppArgb, both work if I convert back from bitmap to byte[].
However when I'm trying to feed the converted bitmap into:
using (var g = Graphics.FromImage(bitmap))
{
// add custom text to image
}
For Format16bppArgb1555 I get an "out of memory" exception on the "using" line when it tries to create Graphics object using .FromImage(). The exception reads:
Message = "Out of memory."
Source = "System.Drawing"
and for Format32bppArgb the result is a corrupted image with my custom text on top of it.
Is it possible to get one of them to work? Alternatively, is there a fast way of converting byte[] to image, adding text and converting result back to byte[] again?
I tried using Magick.NET (Q8-x64) which enabled me to do all of the above only it was really slow. Slower than the regular method:
- convert byte[] to MemoryStream
- get bitmap from Image.FromStream()
- add text
- bitmap.Save() to MemoryStream
- memoryStream.ToArray()
Edit 2: probably worth to mention that the original PNG images comes from HTML5 Canvas .ToDataUrl() method.