Home >Backend Development >C++ >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!