0

I have a little problem to convert byte array to Bitmap. Here is my exception:

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll

My code:

public static System.Drawing.Bitmap ByteToImage(byte[] data)
{
    System.Drawing.Bitmap bmp;
    using (var ms = new MemoryStream(data))
    {
        bmp = new System.Drawing.Bitmap(ms);
    }
    return bmp;
}

Bitmap b = ByteToImage(editor1.system.Tiles[0].ImageData);
Form f = new Form();
f.BackgroundImage = b;
f.Show();

I need to load a serialized byte array on the list and convert to an image at runtime.

If I save the bitmap

b.Save(@"C:\test.png");

It works if I try to load bitmap at runtime I get this error.

4
  • How do you get your bytes? You did not show that. Commented Dec 18, 2016 at 8:33
  • What is editor1? What is system? Commented Dec 18, 2016 at 8:34
  • @Happypig375 editor1 is a my userControl, system is a library for serialize all element, contains list, struct and more. Commented Dec 18, 2016 at 9:02
  • 1
    It is failing because the array data does not contain valid image data. The usually occurs because you don't have all the data or you used a stream method that didn't use Encoding.UTF8. The default encoding (even though Microsoft is UTF8) is actually jASCII which will alter binary data. I usually start by verifying the number of bytes in the data matches the number of bytes of where the source of the image came from. The find where the byte count changed. Commented Dec 18, 2016 at 11:21

1 Answer 1

1

Use the bellow code, it will resolve your issue.

    public static Image FormatImage(Image img, int outputWidth, int outputHeight)
    {

        Bitmap outputImage =null;
        Graphics graphics = null;
        try
        {
            outputImage = new Bitmap(outputWidth, outputHeight, System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
            graphics = Graphics.FromImage(outputImage);
            graphics.DrawImage(img, new Rectangle(0, 0, outputWidth, outputHeight),
            new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);

            return outputImage;
        }
        catch (Exception ex)
        {                
           return img;
        }

}

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.