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

How to Encode an Image to a Base64 String in C#?

Mary-Kate Olsen
Release: 2025-01-06 14:45:41
Original
132 people have browsed it

How to Encode an Image to a Base64 String in C#?

Encode an Image to Base64 Using C#

Many applications require the ability to embed images within other formats, such as JSON or XML. In C#, converting an image to a base64 string allows for easy storage and transmission of image data.

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

  1. Load the image from the specified path using Image.FromFile(Path).
  2. Create a MemoryStream object to store the image's byte representation, and then use image.Save(m, image.RawFormat) to save the image to the stream.
  3. Convert the stream's byte array to a base64 string using Convert.ToBase64String(imageBytes).

Here is an example implementation to convert an image located at "C:/image/1.gif" to a base64 string:

using (Image image = Image.FromFile("C:/image/1.gif"))
{
    using (MemoryStream m = new MemoryStream())
    {
        image.Save(m, image.RawFormat);
        byte[] imageBytes = m.ToArray();

        // Convert byte[] to Base64 String
        string base64String = Convert.ToBase64String(imageBytes);
        return base64String;
    }
}
Copy after login

The above is the detailed content of How to Encode an Image 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