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

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

Barbara Streisand
Release: 2025-01-06 14:58:41
Original
420 people have browsed it

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

Convert an Image to Base64 String in C#

Converting an image from a local file path to a base64 string in C# enables you to embed the image's data directly within your code. This is particularly useful for scenarios like sending images via email, displaying them within web content, or storing them in a database.

To achieve this conversion, you can leverage the following steps:

  1. Use the Image.FromFile method to load the image from the specified path on the user's computer. For example, if the image is located at the path C:/image/1.gif, you would write:

    using (Image image = Image.FromFile(@"C:/image/1.gif"))
    {
        // ...
    }
    Copy after login
  2. Create a MemoryStream object to capture the image's data in a buffer. Save the image to the memory stream using the Image.Save method, specifying the image's original format:

    using (MemoryStream m = new MemoryStream())
    {
        image.Save(m, image.RawFormat);
        byte[] imageBytes = m.ToArray();
    }
    Copy after login
  3. Convert the byte array representing the image data to a base64 string using the Convert.ToBase64String method:

    string base64String = Convert.ToBase64String(imageBytes);
    Copy after login
  4. The resulting base64String is a representation of the image data in base64 format, which can be used as needed. For example, you can embed it within a data URI like:

    data:image/gif;base64,/9j/4AAQSkZJRgABAgEAYABgAAD..
    Copy after login

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