Home > Backend Development > C++ > How to Encode Images to Base64 Strings from File Paths in C#?

How to Encode Images to Base64 Strings from File Paths in C#?

DDD
Release: 2025-01-06 14:56:40
Original
258 people have browsed it

How to Encode Images to Base64 Strings from File Paths in C#?

Encoding Images to Base64 Strings in C# from File Paths

In C#, you can convert an image selected by its path on the user's computer into a base64 string. This allows you to embed the image as a data URI within your application or send it over a network.

One way to achieve this is as follows:

  1. Load the image into an Image object using Image.FromFile(Path).
  2. Create a MemoryStream object to store the encoded image.
  3. Use image.Save(m, image.RawFormat) to save the image to the memory stream, maintaining its original file format.
  4. Convert the image bytes stored in the memory stream to a base64 string using Convert.ToBase64String(imageBytes).
  5. Return the base64 string.

Here's an example code to demonstrate:

using (Image image = Image.FromFile(Path))
{
    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

By applying this technique, you can transform any image on the user's computer into a base64 string, enabling you to manage and share images in a variety of scenarios.

The above is the detailed content of How to Encode Images to Base64 Strings from File Paths 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