我们的代码在 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;
}