asp.net : A generic error occurred in GDI+

烈酒焚心 提交于 2019-11-29 00:44:47

Instead of writing directly to files, save your bitmap to a MemoryStream and then save the contents of the stream to disk. This is an old, known issue and, frankly, I don't remember all the details why this is so.

 MemoryStream mOutput = new MemoryStream();
 bmp.Save( mOutput, ImageFormat.Png );
 byte[] array = mOutput.ToArray();

 // do whatever you want with the byte[]

In your case it could be either

private void UploadImage(string uploadedImage)
{
    // Convert Base64 String to byte[]
    byte[] imageBytes = Convert.FromBase64String(uploadedImage);

    string uploadPath = Server.MapPath("..\\uploads\\") + DateTime.Now.Ticks.ToString() + ".jpeg";

    // store the byte[] directly, without converting to Bitmap first 
    using ( FileStream fs = File.Create( uploadPath ) )
    using ( BinaryWriter bw = new BinaryWriter( fs ) )
       bw.Write( imageBytes );
}    

or

private void UploadImage(string uploadedImage)
{
    // Convert Base64 String to byte[]
    byte[] imageBytes = Convert.FromBase64String(uploadedImage);
    MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

    System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)Image.FromStream(ms);

    string uploadPath = Server.MapPath("..\\uploads\\") + DateTime.Now.Ticks.ToString() + ".jpeg";
    ms.Close();

    // convert to image first and store it to disk
    using ( MemoryStream mOutput = new MemoryStream() )
    {  
        bitmap.Save( mOutput, System.Drawing.Imaging.ImageFormat.Jpeg);
        using ( FileStream fs = File.Create( uploadPath ) )
        using ( BinaryWriter bw = new BinaryWriter( fs ) )
            bw.Write( mOutput.ToArray() );
    }
}    

Furthermore I think it's worth pointing out that when MemoryStream is used, stream must always be closed and save method MUST be called before the stream closure

 byte[] byteBuffer = Convert.FromBase64String(Base64String);
 MemoryStream memoryStream = new MemoryStream(byteBuffer);
 memoryStream.Position = 0;
 Bitmap bmpReturn = (Bitmap)Bitmap.FromStream(memoryStream);
 bmpReturn.Save(PicPath, ImageFormat.Jpeg);
 memoryStream.Close();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!