GDI+中发生一般性错误之图片转化为字节数组

项目中前一次遇到字节数组转化为图片时偶尔出现“GDI+中发生一般性错误”,这回是图片转化为字节数组时出现这种情况。经研究解决办法如下,原代码(出错代码)如下:

1.public static  byte[] imageToByteArray(Image imageIn)

2.{

3.      using (MemoryStream ms = new MemoryStream())

4.      {

5.            if (imageIn != null)

6.            {                  

7.                  imageIn.Save(ms,ImageFormat.Jpeg);                    

8.            }

9.       return ms.ToArray();               

10.     }

11.}

 

方法一:

1.public static  byte[] imageToByteArray(Image imageIn)

2.{

3.     using (MemoryStream ms = new MemoryStream())

4.     {

5.           if (imageIn != null)

6.           {

7.                  Bitmap t=new Bitmap (imageIn);

8.                  t.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);                   

9.           }

10.     return ms.ToArray();               

11.     }

12.}

 

方法二:

1.public static  byte[] imageToByteArray(Image imageIn)

2.{

3.     using (MemoryStream ms = new MemoryStream())

4.     {

5.            if (imageIn != null)

6.            {                  

7.                 Bitmap pic = new Bitmap(imageIn.Width, imageIn.Height);

8.                 Graphics g = Graphics.FromImage(pic);

9.                 g.DrawImage(imageIn, 0, 0, imageIn.Width, imageIn.Height);

10.                 g.Dispose();

11.                 pic.Save(ms, ImageFormat.Jpeg);

12.                 pic.Dispose();                   

13.            }

14.     return ms.ToArray();               

15.      }

16.}

你可能感兴趣的:(字节数组)