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

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

Barbara Streisand
Barbara StreisandOriginal
2025-01-05 16:49:08868browse

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

Converting a Base64 String to an Image and Saving It

When working with Base64-encoded images, it can be challenging to convert them into actual image files. To address this, let's explore a modified code snippet that effectively converts a Base64 string into an image and saves it for storage:

protected void SaveMyImage_Click(object sender, EventArgs e)
{
    string imageUrl = Hidden1.Value;
    string saveLocation = Server.MapPath("~/PictureUploads/whatever2.png");

    HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
    WebResponse imageResponse = imageRequest.GetResponse();

    Stream responseStream = imageResponse.GetResponseStream();
    byte[] imageBytes;

    using (var br = new BinaryReader(responseStream))
    {
        var imageString = br.ReadString();
        imageBytes = Convert.FromBase64String(imageString);
    }

    responseStream.Close();
    imageResponse.Close();

    Image image = Image.FromStream(new MemoryStream(imageBytes));

    FileStream fs = new FileStream(saveLocation, FileMode.Create);
    image.Save(fs, ImageFormat.Png);
    fs.Close();
}

In this modified code:

  1. Base64 Conversion: We extract the Base64 string from the response stream using br.ReadString().
  2. Image Object Creation: We convert the Base64 string into a byte array, which is then used to create an Image object.
  3. Image Saving: Instead of writing the raw bytes to a file, we save the image object directly to the desired location using image.Save(). This ensures the image is saved in the specified format (PNG in this case).

The above is the detailed content of How to 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