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.