首页 > 解决方案 > 在 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);

预期结果:字节数组转换为图像

标签: .netazureazure-functionscsx

解决方案


要在电子邮件中嵌入图像,您不需要使用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}");
        }
    }
}

调用该函数后,我可以收到一封新电子邮件jialinjun@gmail.com在此处输入图像描述


推荐阅读