1

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:

  1. convert byte[] to MemoryStream
  2. get bitmap from Image.FromStream()
  3. add text
  4. bitmap.Save() to MemoryStream
  5. memoryStream.ToArray()

Edit 2: probably worth to mention that the original PNG images comes from HTML5 Canvas .ToDataUrl() method.

Alex E
  • 735
  • 2
  • 7
  • 15
  • So the exceptions happen in `// add custom text to image` ? Can we see that then? – pijemcolu Jun 26 '16 at 20:57
  • the exception is thrown on Graphics.FromImage(bitmap), before it can reach the "add custom text to image". I updated my question with this info. – Alex E Jun 26 '16 at 23:32
  • that outOfMemoryException is rather delicately explained in the upvoted answer in [this question](http://stackoverflow.com/questions/25723855/outofmemoryexception-out-of-memory-system-drawing-graphics-fromimage). I personally use WriteableBitmap class with WriteableBitmapEx extension. You might want to look into that. – pijemcolu Jun 27 '16 at 16:42
  • Thanks @pijemcolu, I tried your method with WriteableBitmap and ext: var wb = BitmapFactory.New(h, w).FromByteArray(image); wb.Lock(); var bitmap = new Bitmap(wb.PixelWidth, wb.PixelHeight, wb.BackBufferStride, PixelFormat.Format32bppPArgb, wb.BackBuffer); if I output bitmap right here, it comes out corrupted just like in my example in original question – Alex E Jun 28 '16 at 04:20

0 Answers0