image-processing - 如何处理嵌入在电子邮件中的图像并调整大小
问题描述
我们的代码在 Xamarin(和 .Net Standard 2.0)之外运行良好,但在尝试在 Xamarin Forms 应用程序中执行时失败并出现平台不受支持的错误(在 Image.FromStream(...))行。此代码处理保存在数据库中的电子邮件并尝试调整图像大小,然后重新输出消息正文以供 Xamarin WebView 控件使用。如果 Image.FromStream() 不适合我们,我们如何解决这个问题?
这是执行处理的代码(可以假设比率为 50 作为示例):
/// <summary>
/// Converts images in an email to Base64 imbedded source
/// </summary>
/// <param name="newMessage">MimeMessage that represents the loaded email message</param>
/// <param name="bodyHtml">Body property of that message</param>
/// <param name="imageResizeRatio">New ratio for image</param>
/// <returns>String used for new body for UI to display</returns>
private static string PopulateInlineImages(MimeMessage newMessage, string bodyHtml, double imageResizeRatio = 1)
{
// encode as base64 for easier downloading/storage
if (bodyHtml != null)
{
foreach (MimePart att in newMessage.BodyParts)
{
if (att.ContentId != null && att.Content != null && att.ContentType.MediaType == "image" && (bodyHtml.IndexOf("cid:" + att.ContentId, StringComparison.Ordinal) > -1))
{
byte[] b;
using (var mem = new MemoryStream())
{
att.Content.DecodeTo(mem);
b = ReduceSize(mem, imageResizeRatio);
//b = mem.ToArray();
}
string imageBase64 = "data:" + att.ContentType.MimeType + ";base64," + System.Convert.ToBase64String(b);
bodyHtml = bodyHtml.Replace("cid:" + att.ContentId, imageBase64);
}
}
}
return bodyHtml;
}
private static byte[] ReduceSize(Stream stream, double imageResizeRatio = 1)
{
Image source = Image.FromStream(stream);
Image thumbnail = source.GetThumbnailImage((int)(source.Width * imageResizeRatio), (int)(source.Height * imageResizeRatio), AbortCallback, IntPtr.Zero);
using (var memory = new MemoryStream())
{
thumbnail.Save(memory, source.RawFormat);
return memory.ToArray();
}
}
private static bool AbortCallback()
{
return false;
}
解决方案
推荐阅读
- c# - ASP.Net 分阶段升级网站
- java - 为什么 write() 控制台输出返回一个字符
- html - 在键盘上切换时展开子菜单
- sql - 我想将这 4 个存储过程合并为一个,因为它们都返回相同的数据(几乎)
- typescript - 类型 '{ 市场:[市场]; 上不存在属性“市场”;在打字稿中
- php - woocommerce多个自定义字段代码
- c# - System.Tuple 和 (,) 有什么区别?
- linux - 需要 .gz 文件的 grep 命令解决方案
- guzzle - guzzle 6 帖子不起作用
- google-ads-api - 使用 Adwords API 忽略属于 REMOVED 广告系列的广告组