Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte array to image conversion

I want to convert a byte array to an image.

This is my database code from where I get the byte array:

public void Get_Finger_print() {     try     {         using (SqlConnection thisConnection = new SqlConnection(@"Data Source=" + System.Environment.MachineName + "\\SQLEXPRESS;Initial Catalog=Image_Scanning;Integrated Security=SSPI "))         {             thisConnection.Open();             string query = "select pic from Image_tbl";// where Name='" + name + "'";             SqlCommand cmd = new SqlCommand(query, thisConnection);             byte[] image =(byte[]) cmd.ExecuteScalar();             Image newImage = byteArrayToImage(image);             Picture.Image = newImage;             //return image;         }     }     catch (Exception) { }     //return null; } 

My conversion code:

public Image byteArrayToImage(byte[] byteArrayIn) {     try     {         MemoryStream ms = new MemoryStream(byteArrayIn,0,byteArrayIn.Length);         ms.Write(byteArrayIn, 0, byteArrayIn.Length);         returnImage = Image.FromStream(ms,true);//Exception occurs here     }     catch { }     return returnImage; } 

When I reach the line with a comment, the following exception occurs: Parameter is not valid.

How can I fix whatever is causing this exception?

like image 520
Tanzeel ur Rahman Avatar asked Feb 07 '12 09:02

Tanzeel ur Rahman


People also ask

What is byte array image?

Images are binary data - this is easily represented as byte arrays. The image in the sample is stored in the database as a BLOB - not a string or location, that is, it is binary data.

How do I print a byte array?

You can simply iterate the byte array and print the byte using System. out. println() method.

What is byte array?

A byte array is simply a collection of bytes. The bytearray() method returns a bytearray object, which is an array of the specified bytes. The bytearray class is a mutable array of numbers ranging from 0 to 256.


2 Answers

You are writing to your memory stream twice, also you are not disposing the stream after use. You are also asking the image decoder to apply embedded color correction.

Try this instead:

using (var ms = new MemoryStream(byteArrayIn)) {     return Image.FromStream(ms); } 
like image 169
Holstebroe Avatar answered Oct 22 '22 11:10

Holstebroe


Maybe I'm missing something, but for me this one-liner works fine with a byte array that contains an image of a JPEG file.

Image x = (Bitmap)((new ImageConverter()).ConvertFrom(jpegByteArray)); 

EDIT:

See here for an updated version of this answer: How to convert image in byte array

like image 42
RenniePet Avatar answered Oct 22 '22 10:10

RenniePet