Here is my code:
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();
using (BinaryReader br = new BinaryReader(responseStream))
{
imageBytes = br.ReadBytes(500000);
br.Close();
}
responseStream.Close();
imageResponse.Close();
FileStream fs = new FileStream(saveLocation, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
try
{
bw.Write(imageBytes);
}
finally
{
fs.Close();
bw.Close();
}
}
}
The top imageUrl declartion is taking in a Base64 image string, and I want to convert it into an image. I think my set of code only works for images like "www.mysite.com/test.jpg" not for a Base64 string. Anybody have some suggestions? Thanks!
Here is working code for converting an image from a base64 string to an
Image
object and storing it in a folder with unique file name:Here is what I ended up going with.
You can save Base64 directly into file:
If you have a string of binary data which is Base64 encoded, you should be able to do the following:
You should be able to write the resulting array to a file.
In a similar scenario what worked for me was the following:
ImageTagId
is the ID of the ASP image tag.Here is an example, you can modify the method to accept a string parameter. Then just save the image object with .Save().
It is possible to get an exception
A generic error occurred in GDI+.
when the bytes represent a bitmap. If this is happening save the image before disposing the memory stream (while still inside the using statement).