我想将图像转换为 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);
}
错误是:
Parameter is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Parameter is not valid.
Source Error:
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";
Source File: e:\Practice Projects\FaceDetection\Default.aspx.cs Line: 36
最佳答案
您正在从空流中读取,而不是将现有数据 (imageBytes
)加载到流中。尝试:
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 is not supported在 ASP.NET 上; YMMV.
Caution
Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions. For a supported alternative, see Windows Imaging Components.
关于c# - 将图像转换为 base64,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7240216/