.net - 在 Azure Functions 中将字节数组转换为图像
问题描述
Azure Functions 不支持 System.Drawing,因此无法使用 Image 类将字节数组转换为 Image。那么我们如何在使用 C#Script 的 Azure Functions 中将字节数组转换为图像,其中 System.Drawing 未被识别为有效的命名空间
图像以 BYTE ARRAY 格式存储在数据库中。稍后当需要将字节数组转换为图像以将它们嵌入到电子邮件中时,代码会显示错误,因为 Azure 函数中无法识别图像命名空间。Azure 函数不支持 System.Drawing dll。是否有以下代码的替代方法将字节数组转换为图像:
MemoryStream imageMemoryStream = new MemoryStream(imageFromDatabase.Data);
Image imageFromStream = Image.FromStream(imageMemoryStream);
var inlineImage = new LinkedResource(imageFromStream, imageFromDatabase.ContentType)
{
ContentId = Guid.NewGuid().ToString()
};
att.Value = string.Format("cid:{0}", inlineImage.ContentId);
linkedResources.Add(inlineImage);
预期结果:字节数组转换为图像
解决方案
要在电子邮件中嵌入图像,您不需要使用System.Drawing
. 您只需要将图像内容放入您的电子邮件中。这是我的示例:
public static class Function1
{
[FunctionName("Function1")]
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]HttpRequest req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
// To simplify the test, I diredtly get the image bytes from base64encoded string.
string base64String = "/9j/4gIcSUNDX1BST0ZJT********NjN8uMCgsR4lzsgB7Q6gAggunL9Lgw88jkGAPOlL3kk2gggud11//Z";
byte[] jpg = Convert.FromBase64String(base64String);
using (MemoryStream stream = new MemoryStream(jpg))
{
LinkedResource res = new LinkedResource(stream, MediaTypeNames.Image.Jpeg);
res.ContentId = Guid.NewGuid().ToString();
string htmlBody = $"<html><body><h1>Picture</h1><br><img src=\"cid:{res.ContentId}\" /></body></html>";
AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, Encoding.UTF8, MediaTypeNames.Text.Html);
alternateView.LinkedResources.Add(res);
MailMessage message = new MailMessage(new MailAddress("jack@hanxia.onmicrosoft.com"), new MailAddress("jialinjun@gmail.com"));
message.Subject = "Send email with imgae";
message.AlternateViews.Add(alternateView);
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.office365.com";
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("jack@hanxia.onmicrosoft.com", "***the_password***");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(message);
return (ActionResult)new OkObjectResult($"{htmlBody}");
}
}
}
推荐阅读
- python - 如何从 PyCharm 上相同路径中的模块导入特定功能
- python - Discord.py 我想在嵌入中创建一个随机答案
- android - Kotlin:setText 不起作用
- flutter - 如何使用 BLOC 为对象列表创建流和接收器
- parameters - 水晶报表,期间每一天的相同报表
- java - 我可以在同一个 Android 应用程序中做两个不同的 NavDrawers 吗?
- cuda - Nvidia Tesla T4 张量核心基准测试
- javascript - 如何使用 JS 将删除按钮添加到列中?
- javascript - 我应该如何强制 TypeScript 理解这个数组中不会有任何空值?
- visual-studio - DotNet 5 ClickOnce 缺少程序集