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); }
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!