Home > Backend Development > C++ > How to Convert a Base64 Encoded Image String to a File in C#?

How to Convert a Base64 Encoded Image String to a File in C#?

Linda Hamilton
Release: 2025-01-05 16:55:39
Original
175 people have browsed it

How to Convert a Base64 Encoded Image String to a File in C#?

Converting Base64 Encoded Images to Files

In your scenario, you aim to convert a Base64 encoded image string into an image and save it using C# code. You've provided your current code snippet, but it's configured to handle regular image URLs like "www.mysite.com/test.jpg" rather than Base64 strings.

To address this, here's an alternative approach that allows you to decode and save Base64 images:

public Image LoadImage(string base64Image)
{
    // Convert the Base64 string to a byte array
    byte[] bytes = Convert.FromBase64String(base64Image);

    Image image;
    using (MemoryStream ms = new MemoryStream(bytes))
    {
        // Decode the image from the memory stream and store it in the Image object
        image = Image.FromStream(ms);
    }

    return image;
}

protected void SaveMyImage_Click(object sender, EventArgs e)
{
    // Retrieve the Base64 image string from your input
    string base64Image = Hidden1.Value;

    // Generate an Image object from the Base64 string
    Image image = LoadImage(base64Image);

    // Specify the desired file path and name
    string saveLocation = Server.MapPath("~/PictureUploads/my_image.png");

    // Save the decoded image
    image.Save(saveLocation);
}
Copy after login

Here, the LoadImage method takes a Base64 encoded image string as input, converts it to a byte array, and decodes it into an Image object. The SaveMyImage_Click event handler then calls the LoadImage method to generate the Image object and save it at the specified location.

Note that this code assumes the Base64 string represents a valid image format. If the string is malformed or invalid, an exception may be thrown.

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