从 Base-64 字符串转换为图像时出现异常

Exception when converting to image from Base-64 string

我正在尝试通过单击 ASP.NET 按钮时的图像发送 Highcharts 图表。 我想做的是:

图表转base64图片,代码如下:

  var chart = $('#main-content').highcharts();
    EXPORT_WIDTH = 1000;
    var render_width = EXPORT_WIDTH;
    var render_height = render_width * chart.chartHeight / chart.chartWidth;

    var svg = chart.getSVG({
        exporting: {
            sourceWidth: chart.chartWidth,
            sourceHeight: chart.chartHeight
        }
    });
    var contentToSend = 'data:image/svg+xml;base64,' + window.btoa(svg);
    var hdnField = document.getElementById("MainContent_ChartImage");
    hdnField.value = contentToSend;

下一步是获取 base64 图像值,将其转换为图像并将其附加到邮件中,代码为:

 string textImage = ChartImage.Value;

 var imageData = Convert.FromBase64String(HttpUtility.UrlDecode(data));
 System.Net.Mail.LinkedResource res;
 AlternateView htmlView;
 using (MemoryStream ms = new MemoryStream(imageData, true))
 {
      ms.Position = 0;
      ms.Write(imageData, 0, imageData.Length);
      ms.Seek(0, SeekOrigin.Begin);
      res = new System.Net.Mail.LinkedResource(ms);
      htmlView = AlternateView.CreateAlternateViewFromString("<html><body><img src='cid:imageReport' width='100%' ></body></html>", null, "text/html");
      res.ContentId = "imageReport";
      htmlView.LinkedResources.Add(res);
      MailMessage mailMsg = new MailMessage();
      SmtpClient client = new SmtpClient();

      // ...

      mailMsg.IsBodyHtml = true;
      mailMsg.AlternateViews.Add(htmlView);
      client.Send(mailMsg);
 }

但是方法 Convert.FromBase64String 抛出异常

{"The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. "}

然而,当我删除 'data:image/svg+xml;base64,' 然后转换它时,它不会抛出异常,但图像不会出现。我该怎么办?

谢谢

去掉字符串的开头部分:"data:image/svg+xml;base64," 那部分不是 base64,剩下的就是。您也不需要使用 HttpUtility.UrlDecode。

您应该将 TransferEncoding 指定为 Base64:

res.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;

尽管如此,there are some strong caveats to using SVG in email。因此,您可能需要考虑使用其他格式,例如 JPG 或 PNG。如果那是您选择的路线,您将需要使用库来转换格式。

经过多次研究我找到了解决方案,主要问题是并非所有客户端电子邮件都支持数据 URI: What is Data URI support like in major email client software?

我试图从 outlook 2016 打开邮件,但它不受支持,当我从 hotmail.com 打开时它有效..

代码是:

MailMessage mailMsg = new MailMessage();
SmtpClient client = new SmtpClient();
var imageData = Convert.FromBase64String(data);
var contentId = Guid.NewGuid().ToString();
var linkedResource = new LinkedResource(new MemoryStream(imageData), "image/svg+xml");
linkedResource.ContentId = contentId;
linkedResource.TransferEncoding = TransferEncoding.Base64;
var body = string.Format("<img src=\"cid:{0}\" />", contentId);
var htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
 htmlView.LinkedResources.Add(linkedResource);
 mailMsg.AlternateViews.Add(htmlView);