Home >Backend Development >C++ >How Can I Convert a Base64 String to an Image and Save It?

How Can I Convert a Base64 String to an Image and Save It?

DDD
DDDOriginal
2025-01-05 20:04:48325browse

How Can I Convert a Base64 String to an Image and Save It?

Converting a Base 64 String to an Image and Saving It

When attempting to convert a base 64 string into an image using the provided code, it may not function correctly because the code is designed to download and save an image from a URL. To address this issue and process base 64 strings, consider the following approach:

Modify the code to receive a base 64 string as a parameter. Once converted to an image, it can be saved using the image.Save(...) method.

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

    Image image;
    using (MemoryStream ms = new MemoryStream(bytes))
    {
        image = Image.FromStream(ms);
    }

    return image;
}

Handle potential exceptions. For instance, if the bytes represent a bitmap, a "A generic error occurred in GDI ." exception may occur. To work around this, save the image before disposing the memory stream (while still within the using statement):

image.Save("output.png", ImageFormat.Png);

Now, with these modifications, you can seamlessly convert base 64 strings into images and save them to your desired location.

The above is the detailed content of How Can I Convert a Base64 String to an Image and Save It?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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