c# - 将图像转换为 base64,反之亦然

标签 c# .net asp.net

我想将图像转换为 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/

相关文章:

c# - 如何使用 .NET 快速获取目录中最旧的文件?

c# - 在 C# 中使不安全代码变得安全

asp.net - NHibernate 问题 "Unable to find the requested .Net Framework Data Provider. It may not be installed. "

javascript - 将 html 表中的输入文本动态传递给 Javascript 函数

c# - C# 中的 Web 服务和属性

c# - 502 请求 azure 内的支付服务 'website'

c# - .Net TPL : Limited Concurrency Level Task scheduler with task priority?

c# - 从对象继承类

c# - 创建一个易于理解的双向链表

javascript - 如何通过 AJAX( native JS)调用 ASP.NET WebMethod