Home > Backend Development > C++ > How to Convert a Base64 Encoded Image String to an Image in ASP.NET?

How to Convert a Base64 Encoded Image String to an Image in ASP.NET?

Mary-Kate Olsen
Release: 2025-01-05 19:58:41
Original
178 people have browsed it

How to Convert a Base64 Encoded Image String to an Image in ASP.NET?

Converting a Base64 Encoded Image String to Image

Your provided ASP.NET code snippet attempts to save an image from a URL. However, you've encountered an issue because the URL provided is a Base64 encoded string, not a direct image URL.

To resolve this, you need to decode the Base64 string into binary data and then create an Image object from the binary data. Here's an example of how you can modify your code:

protected void SaveMyImage_Click(object sender, EventArgs e)
{
    // Get the Base64 encoded image string from the hidden input field
    string base64ImageString = Hidden1.Value;

    // Convert the Base64 string to binary data
    byte[] imageBytes = Convert.FromBase64String(base64ImageString);

    // Create a memory stream from the binary data
    using (MemoryStream ms = new MemoryStream(imageBytes))
    {
        // Create an Image object from the memory stream
        Image image = Image.FromStream(ms);

        // Save the image to the specified location
        string saveLocation = Server.MapPath("~/PictureUploads/whatever2.png");
        image.Save(saveLocation);
    }
}
Copy after login

Additional Notes for Handling Bitmap Exceptions

If you encounter a "A generic error occurred in GDI " exception when trying to decode the Base64 string, it may be because the bytes represent a bitmap image. To resolve this, save the image before disposing the memory stream:

// Create a memory stream from the binary data
using (MemoryStream ms = new MemoryStream(imageBytes))
{
    // Save the image to the memory stream
    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); // Replace "Png" with the appropriate image format

    // Create an Image object from the memory stream
    image = Image.FromStream(ms);

    // Dispose the memory stream
    ms.Dispose();
}
Copy after login

The above is the detailed content of How to Convert a Base64 Encoded Image String to an Image in ASP.NET?. 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