Home > Backend Development > C++ > How Can I Save a Base64 Image String to a File?

How Can I Save a Base64 Image String to a File?

Susan Sarandon
Release: 2025-01-06 02:13:47
Original
267 people have browsed it

How Can I Save a Base64 Image String to a File?

Converting Base64 Strings to Images

One may encounter difficulties when attempting to save Base64 image strings to files, especially if relying on methods that are designed for image URLs. A solution is available to transform Base64 strings into image objects, before saving the objects to the desired file path.

An example method, accepting a string parameter, is provided below:

public Image LoadImage(string base64String)
{
    // Convert Base64 string to bytes
    byte[] bytes = Convert.FromBase64String(base64String);

    Image image;
    using (MemoryStream ms = new MemoryStream(bytes))
    {
        // Create image object from memory stream
        image = Image.FromStream(ms);
    }

    return image;
}
Copy after login

To save the image to a file:

using (Image image = LoadImage(base64String))
{
    string saveLocation = Server.MapPath("~/PictureUploads/whatever.png");
    image.Save(saveLocation);
}
Copy after login

Note that an exception may arise ("A generic error occurred in GDI ") when dealing with bitmap images. In such cases, it's recommended to save the image before disposing the memory stream.

The above is the detailed content of How Can I Save a Base64 Image String to a File?. 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