I want to convert an image to base64 and back to image again.
Here is the code which i tried so far and the error also. Any suggestions please?
public void Base64ToImage(string coded)
{
System.Drawing.Image finalImage;
MemoryStream ms = new MemoryStream();
byte[] imageBytes = Convert.FromBase64String(coded);
ms.Read(imageBytes, 0, imageBytes.Length);
ms.Seek(0, SeekOrigin.Begin);
finalImage = System.Drawing.Image.FromStream(ms);
Response.ContentType = "image/jpeg";
Response.AppendHeader("Content-Disposition", "attachment; filename=LeftCorner.jpg");
finalImage.Save(Response.OutputStream, ImageFormat.Jpeg);
}
The error is :
Parameter is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Parameter is not valid.
Source Error:
Line 34: ms.Read(imageBytes, 0, imageBytes.Length);
Line 35: ms.Seek(0, SeekOrigin.Begin);
Line 36: finalImage = System.Drawing.Image.FromStream(ms);
Line 37:
Line 38: Response.ContentType = "image/jpeg";
Source File: e:\Practice Projects\FaceDetection\Default.aspx.cs Line: 36
You are reading from an empty stream, rather than loading the existing data (
imageBytes) into the stream. Try:Also, you should endeavour to ensure that
finalImageis disposed; I would propose:And finally, note that System.Drawing is not supported on ASP.NET; YMMV.