我想将图像转换为 Base64,然后再次转换回图像。
这是我到目前为止尝试过的代码以及错误。请问有什么建议吗?
public void Base64ToImage(string coded)
{
System.Drawing.Image finalImage;
MemoryStream ms = new MemoryStream();
byte[] imageBytes = Convert.FromBase64String(coded);
ms.Read(imageBytes, 0, imageBytes.Length);
ms.Seek(0, SeekOrigin.Begin);
finalImage = System.Drawing.Image.FromStream(ms);
Response.ContentType = "image/jpeg";
Response.AppendHeader("Content-Disposition", "attachment; filename=LeftCorner.jpg");
finalImage.Save(Response.OutputStream, ImageFormat.Jpeg);
}
错误是:
参数无效。
描述:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其在代码中的来源的更多信息。
异常详细信息:System.ArgumentException:参数无效。
来源错误:
Line 34: ms.Read(imageBytes, 0, imageBytes.Length);
Line 35: ms.Seek(0, SeekOrigin.Begin);
Line 36: finalImage = System.Drawing.Image.FromStream(ms);
Line 37:
Line 38: Response.ContentType = "image/jpeg";
源文件:e:\Practice Projects\FaceDetection\Default.aspx.cs 行:36
You are reading从空流中加载,而不是加载现有数据(imageBytes
) into溪流。尝试:
byte[] imageBytes = Convert.FromBase64String(coded);
using(var ms = new MemoryStream(imageBytes)) {
finalImage = System.Drawing.Image.FromStream(ms);
}
此外,您还应该努力确保finalImage
被处置;我建议:
System.Drawing.Image finalImage = null;
try {
// the existing code that may (or may not) successfully create an image
// and assign to finalImage
} finally {
if(finalImage != null) finalImage.Dispose();
}
最后,请注意 System.Drawing不支持在 ASP.NET 上; YMMV。
Caution
不支持在 Windows 或 ASP.NET 服务中使用 System.Drawing 命名空间中的类。尝试在这些应用程序类型之一中使用这些类可能会产生意外的问题,例如服务性能下降和运行时异常。有关受支持的替代方案,请参阅 Windows 成像组件。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)