Base64 編碼是一種二進制到文本的編碼方案,可有效地將二進制數據轉換為 ASCII 字符,為數據交換提供通用格式。在某些情況下,我們可能需要將JPG或PNG圖像轉換為 Base64 字符串數據。在這篇博文中,我們將學習如何在 C# 中將圖像轉換為 Base64。
Aspose.SVG最新下載(qun:666790229)https://www.evget.com/product/4207/download
Base64 編碼是一種二進制到文本的編碼方案,可有效地將二進制數據轉換為 ASCII 字符,為數據交換提供通用格式。在某些情況下,我們可能需要將JPG或PNG圖像轉換為 Base64 字符串數據。在這篇博文中,我們將學習如何在 C# 中將圖像轉換為 Base64。
圖像到 Base64 轉換器 C# API
我們將使用Aspose.SVG for .NET API將圖像轉換為 Base64 。它專為處理和渲染SVG文件而設計。它允許開發人員創建、讀取、更新、轉換和解析 SVG 文件。
請下載API的DLL或使用NuGet安裝。
PM> Install-Package Aspose.SVG
在 C# 中將圖像轉換為 Base64
我們可以按照以下步驟在 C# 中以編程方式輕松將圖像轉換為 Base64:
- 加載輸入 JPG 圖像。
- 創建SVGDocument類的實例。
- 使用SVGImageElement類創建圖像元素。
- 將圖像轉換為 Base64。
- 將圖像元素添加到 SVG 文檔中。
- 最后,調用save()方法保存SVG文檔。
以下代碼示例展示了如何在 C# 中將 JPG 圖像轉換為 Base64。
// Load an input JPG image var bytes = File.ReadAllBytes(@"C:\Files\Sample_JPG.jpg");// Initialize an SVGDocument object var document = new SVGDocument();// Create an image element var img = (SVGImageElement)document.CreateElementNS("http://www.w3.org/2000/svg", "image");// Convert image to Base64 img.Href.BaseVal = "data:image/png;charset=utf-8;base64," + Convert.ToBase64String(bytes);// Add the image element into the SVG document document.RootElement.AppendChild(img);// Save the SVG document document.Save(@"C:\Files\image-base64.svg");
C# 中的 PNG 到 Base64
同樣,我們可以按照前面提到的步驟將 PNG 圖像轉換為 Base64。不過,我們只需要輸入一張PNG圖片即可,如下所示:
// Load an input JPG image var bytes = File.ReadAllBytes(@"C:\Files\Sample.png");// Initialize an SVGDocument object var document = new SVGDocument();// Create an image element var img = (SVGImageElement)document.CreateElementNS("http://www.w3.org/2000/svg", "image");// Convert image to Base64 img.Href.BaseVal = "data:image/png;charset=utf-8;base64," + Convert.ToBase64String(bytes);// Add the image element into the SVG document document.RootElement.AppendChild(img);// Save the SVG document document.Save(@"C:\Files\image-base64.svg");
結論
在這篇博文中,我們學習了如何在 C# 中將圖像轉換為 Base64 字符串。通過遵循概述的步驟,您可以輕松地將圖像轉換功能集成到您的應用程序中~