Azure 函數是基於事件的無服務器雲服務。您可以使用 Azure 函數中的 Aspose.Drawing for .NET API 根據您的要求繪製矢量圖形或文本。本文介紹如何快速輕鬆地配置 API 以在 Azure Functions 中使用:

創建 Azure Functions 應用程序

首先,請從 Azure Functions 項目模板創建一個 HTTP 觸發器函數,如以下屏幕截圖所示:

Azure Function 中的 System.Drawing

添加 Aspose.Drawing NuGet 包到項目中

Aspose.Drawing for .NET API 託管在 NuGet 庫中。請使用用戶界面或使用以下安裝命令在項目中添加依賴項:

PM> Install-Package Aspose.Drawing

添加用於繪製圖像的代碼

然後,您需要添加少量代碼來繪製圖像,因為 API 會處理次要細節。請將以下代碼替換到 Function1.cs 文件中,以繪製漸變並返回 HTTP 請求的輸出圖像:

// C# 代碼繪製矢量圖形和文本,並在您的 Azure 函數中創建圖像以在雲上運行。

using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace AzureFunctionApp1
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ExecutionContext context)
        {
            Aspose.Drawing.License license = new Aspose.Drawing.License();
            license.SetLicense(Path.Combine(context.FunctionAppDirectory, "Aspose.Drawing.NET.lic"));

            return new FileStreamResult(Draw(ImageFormat.Png), "image/png");
        }

        static Stream Draw(ImageFormat format)
        {
            Bitmap bitmap = new Bitmap(1000, 800, PixelFormat.Format32bppPArgb);
            Graphics graphics = Graphics.FromImage(bitmap);

            Brush brush = new LinearGradientBrush(new Point(0, 0), new Point(1000, 800), Color.Red, Color.Blue);
            graphics.FillEllipse(brush, 100, 100, 800, 600);

            MemoryStream result = new MemoryStream();
            bitmap.Save(result, format);
            result.Seek(0, SeekOrigin.Begin);
            return result;
        }
    }
}

現在,將帶有 Aspose.Drawing 許可信息的 Aspose.Drawing.NET.lic 許可文件複製到項目目錄,從解決方案資源管理器中打開該文件屬性,並將“複製到輸出目錄”設置為“始終複製”。如果您沒有許可證,那麼您可以申請免費評估許可證以全面測試 API。

將項目發佈到 Azure

然後,按照快速入門:使用 Visual Studio 在 Azure 中創建您的第一個函數 中所述將您的項目發佈到 Azure。

在 Azure 中測試函數

在瀏覽器的地址欄中,將字符串 /api/Function1 附加到基本 URL 並運行請求(完整請求將類似於 https://azurefunctionapp123456789.azurewebsites.net/api/Function1)。

最後,你會看到如下的繪製結果:

Azure 函數中的 Aspose.Drawing

結論

在本文中,你了解瞭如何在 Azure 函數中使用 Aspose.Drawing for .NET API。 System.Drawing 命名空間在 Azure 函數中可能存在兼容性問題,因此您可以輕鬆使用 Aspose.Drawing API 而不會出現任何問題。此外,如有任何疑慮,您可以隨時通過 免費支持論壇 與我們聯繫。

也可以看看