Home > Backend Development > C++ > How to Convert an Image File Path to a Base64 String in C#?

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

Susan Sarandon
Release: 2025-01-06 14:57:40
Original
892 people have browsed it

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

Convert Image to Base64 String

Converting an image to a base64 string allows you to embed images within other data, such as HTML or JavaScript. In this context, we'll explore how to convert an image from a file path to a base64 string in C#.

Solution:

To convert an image to a base64 string in C#, follow these steps:

  1. Load the image from the file path: Use the Image.FromFile method to load the image from the specified path.
  2. Create a memory stream: Use a MemoryStream to store the image in memory.
  3. Save the image to the memory stream: Call the Save method on the image and pass in the memory stream as the destination.
  4. Retrieve the image bytes: Convert the memory stream to a byte array using the ToArray method.
  5. Convert the byte array to a base64 string: Use the Convert.ToBase64String method to encode the byte array into a base64 string.

Code Example:

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;
                }
            }
        }
    }
}
Copy after login

The above is the detailed content of How to Convert an Image File Path to a Base64 String in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template