asp.net : A generic error occurred in GDI+

后端 未结 2 1920
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 14:44

I create an asp.net 4.0 web application which has a web service for uploading images. I am uploading images by sending the image in form of Base64 string from my mobile app

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-15 15:15

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

提交回复
热议问题