This question already has an answer here:
- C# Base64 String to JPEG Image 4 answers
As an example I have converted a canvas element with a re-sized image and posted into a hidden input field that's now encoded as
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...
This value then posted to the same page which I need to convert this string into an image and save onto the server.
Code Behind File (upload.aspx)
protected void btnUpload_Click(object sender, EventArgs e)
{
HttpPostedFile filePosted = Request.Files["newinput"];
string base64String = filePosted.ToString();
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
//I DONT KNOW HOW TO WRITE ABOVE INTO THE SaveAs CONDITION BELOW
if (filePosted != null && filePosted.ContentLength > 0)
{
string fileNameApplication = Path.GetFileName(filePosted.FileName);
string fileExtensionApplication = Path.GetExtension(fileNameApplication);
// generating a random guid for a new file at server for the uploaded file
string newFile = Guid.NewGuid().ToString() + fileExtensionApplication;
// getting a valid server path to save
string filePath = Path.Combine(Server.MapPath("~/Assets/") + Request.QueryString["id"] + "/", newFile);
if (fileNameApplication != String.Empty)
{
filePosted.SaveAs(filePath);
}
}
I'm pretty sure I need to convert this the imagedata to a binary file before saving on the server but I can't quite get how I need to amend the code above. Any ideas? The code to save to the server doesn't work.
Once I have converted this to an image and changed it's name as above - I'm storing this back to a database via LINQ - with a URL appended to it.
Any help would be greatly appreciated.
Hope below functions helps.
EDIT 1 -
From the comments it seems that you are getting base64 string and you need to save it as image on server and then whenever required you need to show that image using physical server path.
Ok. Base64ToImage will give you image for your base64 string. You can save it on server using
And this "PATH" you have supplied or created can be stored in DB as URL, which you can use at the time of display.
Note: Make sure that you have write access to folder where you are saving image.
EDIT-2 Your function should look like below. Please put validation code, error handling as required.