3

I have a method which saves the image from a panel. This method is using Bitmap class. I wants that my method should return byte array of the image.

 private byte[] SaveImage()
    {
        byte[] byteContent = null;
        using (Bitmap bitmap = new Bitmap(500, 500))
        {
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                Rectangle rectangle = myPanel.Bounds;
                Point sourcePoints = myPanel.PointToScreen(new Point(myPanel.ClientRectangle.X, myPanel.ClientRectangle.Y));
                g.CopyFromScreen(sourcePoints, Point.Empty, rectangle.Size);
            }

            string fileName = @"E:\\MyImages.Jpg";
            bitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        return byteContent;
    }
user1399377
  • 469
  • 2
  • 7
  • 19

1 Answers1

20

You'll need to use a MemoryStream to serialize the bitmap to an image format and get the bytes;

using (Bitmap bitmap = new Bitmap(500, 500))
{
    using (Graphics g = Graphics.FromImage(bitmap))
    {
        ...
    }

    using (var memoryStream = new MemoryStream())
    {
        bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        return memoryStream.ToArray();
    }
}

There are multiple output formats to choose from, you may instead want Bmp or MemoryBmp.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294