首頁 > 後端開發 > C++ > 如何在 C# 中將圖像檔案路徑轉換為 Base64 字串?

如何在 C# 中將圖像檔案路徑轉換為 Base64 字串?

Susan Sarandon
發布: 2025-01-06 14:57:40
原創
925 人瀏覽過

How to Convert an Image File Path to a Base64 String in C#?

將圖片轉換為Base64 字串

將圖片轉換為Base64 字串可讓您將圖片嵌入到其他資料中,例如HTML或JavaScript 。在這種情況下,我們將探討如何在 C# 中將映像從檔案路徑轉換為 Base64 字串。

解決方案:

將影像轉換為C# 中的base64 字串,請按照以下步驟操作:

  1. 從檔案載入映像路徑:使用Image.FromFile方法從指定路徑載入映像。
  2. 建立記憶體流:使用MemoryStream將映像儲存在記憶體中。
  3. 將影像儲存到記憶體流:對影像呼叫 Save 方法,並將記憶體流作為目的地。
  4. 擷取影像位元組:使用 ToArray 方法將記憶體流轉換為位元組數組。
  5. 將位元組陣列轉換為base64 字串: 使用Convert.ToBase64String方法將位元組陣列編碼為base64 string.

程式碼範例🎜>程式碼範例:

using System;
using System.Drawing;
using System.IO;

namespace ImageToBase64
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"C:\Users\User\Documents\test.jpg";

            // Create a data URI
            string base64String = ToBase64(path);
            Console.WriteLine(base64String);
        }

        /// <summary>
        /// Converts an image to a base64 string.
        /// </summary>
        /// <param name="path">The file path of the image.</param>
        /// <returns>A base64 string representing the image.</returns>
        public static string ToBase64(string path)
        {
            using (Image image = Image.FromFile(path))
            {
                using (MemoryStream m = new MemoryStream())
                {
                    image.Save(m, image.RawFormat);
                    byte[] imageBytes = m.ToArray();
                    string base64String = Convert.ToBase64String(imageBytes);
                    return base64String;
                }
            }
        }
    }
}
登入後複製

以上是如何在 C# 中將圖像檔案路徑轉換為 Base64 字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板