使用位图问题保存图片

时间:2016-12-14 18:45:27

标签: c# bitmap

我有有效的base64图像。我将其转换为图像。

使用Image.Save(Path)保存 我有Gdi +错误。

当我尝试使用位图保存时。图像将保存,但图像是完整的黑色像enter image description here

这是我的代码

            var encode = EncodeBase64(model.Base64Photo);

                //model.Base64Photo = model.Base64Photo.Replace("data:image/png;base64,", "").Replace("data:image/jpeg;base64,", "");
                //var imageBytes = Convert.FromBase64String(encode);

                var ms = new MemoryStream(encode);
                var returnImage = Image.FromStream(ms);
                var bitmap = new Bitmap(returnImage);
                bitmap.Save($@"C:\inetpub\wwwroot\Dropbox\Websites\2.fidilio.com\Storage\Images\animal\storage\images\animal\{model.Name}-{model.Email}.jpg", ImageFormat.Jpeg);
                bitmap.Dispose();
     public byte[] EncodeBase64(string data)
    {
        string s = data.Trim().Replace(" ", "+").Replace("-", "+").Replace("/", "+");
        if (s.Length % 4 > 0)
            s = s.PadRight(s.Length + 4 - s.Length % 4, '=');
        return Convert.FromBase64String(s);
    }

我很困惑,问题在哪里

1 个答案:

答案 0 :(得分:2)

看起来你正在用字符串制作内存流,对吗?你应该从字节数组中创建内存流,就像这样。

string s = "iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAAAAAAcD2kOAAACOklEQVR4Ae3YhbIdIQwA0H7YBshzd3d3d7sKJO+vqwxzty4L7UyTkfU9K0CAN/iXQmCBBf5XYIEFFlhggQXeeqr9dDxvVgi/2F+IeoVw/VfgWoVw7VfgF4H/HHbE5L+uEZNLBnt7c3Rao6+w3t0cntUpEeyfJzRAzxF96b5MalB9p5QEdq3RAhG1virL8YgKR6qG+aj4uK5G2q7kxiMw7ZPAK/BpA/a55MYjpq/hUsBrAda9NV+GwxE90EwB07kKW7BSeuV4BBYpSal2U+GVDd5RSW4P67A7CUw3xmAoRV/71rDKiRoQXoKwrU65BB8qRN1X94lg/9KjQ/kaarkyHAp7GtjyNoQdsMOd8DqgGrUuGezawyq8cs+zj66zIxr1BSVMi3waq9QiR/j1TCHMkU0Axz6Xn47l6+g1fFp+7tem6yEtTHdoQmU2B56988R3QwphgxP3QHi1wCCryZOn+svVUpdCPdBwiWFf69UYQqnu3h4NBhGOOHmfi/cBY5hPbZkaty4pHOqOwnIYfU0Zepl0obEcsEBZurc0C+UX7nnyWWD/0GU6DxZbnKlDz+tFxzE12HSZYN/o1xgDTjjbEIYPIR5Sk85mg50dV7Em31I+2NK1DuULljjraJEWIHR1X3xW2D93q49VaZczj4/5FAsFsOSyD8zpYXV68czlh61nIvo/50AErlUIP5D/6aDHCuHFk7OfjpMVma8WWGCBBRZYYIEFFlhggQUWWGCBBRZYYIEFFlhggQV+B9418JaaYBt6AAAAAElFTkSuQmCC";

    var imageBytes = Convert.FromBase64String(s);

    var ms = new MemoryStream(imageBytes);
    var returnImage = Image.FromStream(ms);
    var bitmap = new Bitmap(returnImage);
    //bitmap.Save($@"C:\inetpub\wwwroot\Dropbox\Websites\2.fidilio.com\Storage\Images\animal\storage\images\animal\{model.Name}-{model.Email}.jpg", ImageFormat.Jpeg);
    bitmap.Save(@"c:\temp\img.jpg");
    bitmap.Dispose();