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:
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!