Home >Backend Development >C++ >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; }
To save the image to a file:
using (Image image = LoadImage(base64String)) { string saveLocation = Server.MapPath("~/PictureUploads/whatever.png"); image.Save(saveLocation); }
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!