Home > Backend Development > C++ > How Can I Convert Images to Base64 Strings in C#?

How Can I Convert Images to Base64 Strings in C#?

DDD
Release: 2025-01-06 15:10:41
Original
948 people have browsed it

How Can I Convert Images to Base64 Strings in C#?

Encoding Images as Base64 Strings in C

Converting images to base64 strings is a common need when transmitting images over the internet. Base64 encoding represents binary data in an ASCII character set, making it suitable for use in environments where binary data may not be supported.

Solution: Converting an Image to Base64

To convert an image from a path on a user's computer to a base64 string, simply follow these steps:

  1. Open the image file using Image.FromFile(Path) and store it in an Image object.
  2. Create a MemoryStream object and save the image to the stream using image.Save(m, image.RawFormat).
  3. Convert the MemoryStream to a byte array using m.ToArray().
  4. Finally, use Convert.ToBase64String(imageBytes) to generate the base64 string.

The provided code snippet demonstrates this process:

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 resulting base64 string can be embedded as a data URI using the format data:image/gif;base64,${base64String}, where image/gif represents the image type, and ${base64String} is the base64-encoded image data.

The above is the detailed content of How Can I Convert Images to Base64 Strings 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template