[c#] 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()
        using (SqlConnection thisConnection = new SqlConnection(@"Data Source=" + System.Environment.MachineName + "\\SQLEXPRESS;Initial Catalog=Image_Scanning;Integrated Security=SSPI "))
            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)
        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?

This question is related to c# arrays byte bytebuffer

The answer is

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

Similar questions with c# tag:

Similar questions with arrays tag:

Similar questions with byte tag:

Similar questions with bytebuffer tag: