繁体   English   中英

c#字节到图像ArgumentOutOfRangeException

[英]c# Byte to Image ArgumentOutOfRangeException

将字节数组转换为Bitmap时遇到了一个小问题。 这是我的例外:

mscorlib.dll中发生类型为'System.ArgumentOutOfRangeException'的未处理异常

我的代码:

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();

我需要在列表上加载序列化的字节数组,并在运行时转换为图像。

如果我保存位图

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

如果我尝试在运行时加载位图,则会收到此错误,它可以工作。

使用下面的代码,它将解决您的问题。

    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;
        }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM