Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an image to base64 and vice versa

Tags:

c#

.net

asp.net

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

like image 972
Chandra Eskay Avatar asked Aug 30 '11 07:08

Chandra Eskay


People also ask

How is an image converted to Base64?

To get to a base64 representation:Paint uses its png encoder to convert the bitmap of pixels into a stream of bytes that it compresses and appends headers to so that when it sees those bytes again it knows how to display them. Image is written to disk as series of bytes. You run a base64 encoder on smile. png .

How do I convert a JPEG to Base64?

To convert JPEG to base64 data: Click on "Choose file" and upload the JPEG image from your system. Click on the "Convert" button to convert the JPEG image into base 64 data. You can "Download or Copy" the base 64 code for further use.

Does converting to Base64 reduce quality?

Encoding to/from Base64 is completely lossless. The quality loss happens probably when you save it. To prevent that, use an ImageWriter directly ( ImageIO.


2 Answers

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.

like image 98
Marc Gravell Avatar answered Oct 06 '22 00:10

Marc Gravell


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);
like image 39
dtb Avatar answered Oct 06 '22 01:10

dtb