4

I have a method which saves the image from a panel. This method is using Bitmap class. I want my method to 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;
}
5
  • why are you returning Null byteContent? where in the code are you using or assigning byteContent..? Commented Sep 28, 2012 at 18:54
  • 2
    Save the bitmap to a memory stream and set byteContent = stream.ToArray(); Commented Sep 28, 2012 at 18:55
  • stackoverflow.com/questions/7350679/… Commented Sep 28, 2012 at 18:57
  • @DJ KRAZE Actully i am intentionally returning the null to byte array variable because i don't know how to assign it the byte arrays Commented Sep 28, 2012 at 18:59
  • why did you point out "wpf" as a tag? the bitmap handling in wpf is COMPLETELY different! Commented Sep 28, 2012 at 19:07

1 Answer 1

23

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.