简体   繁体   中英

Convert an image to base64 and vice versa

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:

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

Also, you should endeavour to ensure that finalImage is disposed; I would propose:

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();
}

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

Caution

Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions. For a supported alternative, see Windows Imaging Components.

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

If you want to write the byte array to the MemoryStream , use the MemoryStream.Write Method :

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

Alternatively, you can simply wrap the byte array in a MemoryStream :

MemoryStream ms = new MemoryStream(imageBytes);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM