Convert image to base64 and vice versa

I want to convert the image to base64 and go back to the image again. Here is the code I've tried so far and the error. 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); } 

Mistake:

The parameter is not valid.

Description: An unhandled exception occurred during the execution of the current web request. View the stack trace for more information about the error and its occurrence in the code.

Exception Details: System.ArgumentException: The 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: \ Practical projects \ FaceDetection \ Default.aspx.cs Line: 36

+7
source share
2 answers

You are reading from an empty stream, not loading existing data ( imageBytes ) into the stream. Try:

 byte[] imageBytes = Convert.FromBase64String(coded); using(var ms = new MemoryStream(imageBytes)) { finalImage = System.Drawing.Image.FromStream(ms); } 

In addition, you should strive for finalImage be deleted; I would suggest:

 System.Drawing.Image finalImage = null; try { // the existing code that may (or may not) successfully create an image // and assign to finalImage } finally { if(finalImage != null) finalImage.Dispose(); } 

Finally, note that System.Drawing is not supported on ASP.NET; YMMV.

Attention

Classes in the System.Drawing namespace are not supported for use in a Windows service or ASP.NET. Attempting to use these classes from one of these application types can cause unforeseen problems, such as degraded service performance and runtime exceptions. For a supported alternative, see Windows Image Processing Components.

+7
source

The MemoryStream.Read method reads bytes from a MemoryStream into the specified byte array.

If you want to write an array of bytes to a MemoryStream , use the MemoryStream.Write Method :

 ms.Write(imageBytes, 0, imageBytes.Length); ms.Seek(0, SeekOrigin.Begin); 

Alternatively, you can simply wrap an array of bytes in a MemoryStream :

 MemoryStream ms = new MemoryStream(imageBytes); 
+2
source

All Articles