Xamarin (および .Net Standard 2.0) の外部では正常に動作するコードがありますが、Xamarin Forms アプリケーションで実行しようとすると、(Image.FromStream(...)) 行で platform not supported エラーで失敗します。このコードは、データベースに保存された電子メールを処理し、画像のサイズを変更してから、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;
}