133

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?

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
Tanzeel ur Rahman
  • 1,431
  • 2
  • 9
  • 4
  • Have you checked that the image bytes in your query are valid? You could do a File.WriteAllBytes("myimage.jpg", byteArrayIn) to verify. – Holstebroe Feb 07 '12 at 09:59
  • Would you like to accept one of the answers? [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – Andrew Morton Sep 27 '21 at 17:10

14 Answers14

135

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);
}
Holstebroe
  • 4,993
  • 4
  • 29
  • 45
  • 1
    You may also explicitly make the memory stream non-writable after initialization: new MemoryStream(byteArrayIn, false) – Holstebroe Feb 07 '12 at 09:54
  • 38
    This violates a specification in MSDN for Image.FromStream(), where it says "You must keep the stream open for the lifetime of the Image." See also http://stackoverflow.com/questions/3290060/getting-an-image-object-from-a-byte-array – RenniePet Jan 09 '13 at 10:21
99

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

Community
  • 1
  • 1
RenniePet
  • 11,420
  • 7
  • 80
  • 106
  • 1
    AAAh thanks, Finally a good answer. Why so many answers with memory stream, it cause me so much problem. thanks a lot ! – Julian50 Jun 30 '15 at 11:35
  • Good answer! this can be used in a separate function whereas all other proposals using MemoryStream cannot (Stream must be kept open for lifetime of Image) – A_L Aug 18 '16 at 15:07
30
public Image byteArrayToImage(byte[] bytesArr)
{
    using (MemoryStream memstr = new MemoryStream(bytesArr))
    {
        Image img = Image.FromStream(memstr);
        return img;
    }
}
Cellcon
  • 1,245
  • 2
  • 11
  • 27
Ali Gh
  • 680
  • 7
  • 9
  • While it's not normally a good idea, I put a GC.Collect() before the Memory stream. I was running out of memory when I preloaded a whole lot of large graphic files as bytearrays into memory and then turned them into images during viewing. – Kayot Nov 06 '17 at 01:59
  • 2
    This adds nothing to the [existing answer](https://stackoverflow.com/a/9174069/11683) posted 3 years prior, and suffers from the same problem of disposing the stream prematurely. – GSerg Sep 27 '21 at 22:32
13

I'd like to note there is a bug in solution provided by @isaias-b.

That solution assume that stride is equal to row length. But it is not always true. Due to memory alignments performed by GDI, stride can be greater then row length. This must be taken into account. Otherwise invalid shifted image will be generated. Padding bytes in each row will be ignored.

The stride is the width of a single row of pixels (a scan line), rounded up to a four-byte boundary.

Fixed code:

using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

public static class ImageExtensions
{
    public static Image ImageFromRawBgraArray(this byte[] arr, int width, int height, PixelFormat pixelFormat)
    {
        var output = new Bitmap(width, height, pixelFormat);
        var rect = new Rectangle(0, 0, width, height);
        var bmpData = output.LockBits(rect, ImageLockMode.ReadWrite, output.PixelFormat);

        // Row-by-row copy
        var arrRowLength = width * Image.GetPixelFormatSize(output.PixelFormat) / 8;
        var ptr = bmpData.Scan0;
        for (var i = 0; i < height; i++)
        {
            Marshal.Copy(arr, i * arrRowLength, ptr, arrRowLength);
            ptr += bmpData.Stride;
        }

        output.UnlockBits(bmpData);
        return output;
    }
}

To illustrate what it can lead to, let's generate PixelFormat.Format24bppRgb gradient image 101x101:

var width = 101;
var height = 101;
var gradient = new byte[width * height * 3 /* bytes per pixel */];
for (int i = 0, pixel = 0; i < gradient.Length; i++, pixel = i / 3)
{
    var x = pixel % height;
    var y = (pixel - x) / width;
    gradient[i] = (byte)((x / (double)(width - 1) + y / (double)(height - 1)) / 2d * 255);
}

If we will copy entire array as-is to address pointed by bmpData.Scan0, we will get following image. Image shifting because part of image was written to padding bytes, that was ignored. Also that is why last row is incomplete:

stride ignored

But if we will copy row-by-row shifting destination pointer by bmpData.Stride value, valid imaged will be generated:

stride taken into account

Stride also can be negative:

If the stride is positive, the bitmap is top-down. If the stride is negative, the bitmap is bottom-up.

But I didn't worked with such images and this is beyond my note.

Related answer: C# - RGB Buffer from Bitmap different from C++

lorond
  • 3,856
  • 2
  • 37
  • 52
10

All presented answers assume that the byte array contains data in a known file format representation, like: gif, png or jpg. But i recently had a problem trying to convert byte[]s, containing linearized BGRA information, efficiently into Image objects. The following code solves it using a Bitmap object.

using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
public static class Extensions
{
    public static Image ImageFromRawBgraArray(
        this byte[] arr, int width, int height)
    {
        var output = new Bitmap(width, height);
        var rect = new Rectangle(0, 0, width, height);
        var bmpData = output.LockBits(rect, 
            ImageLockMode.ReadWrite, output.PixelFormat);
        var ptr = bmpData.Scan0;
        Marshal.Copy(arr, 0, ptr, arr.Length);
        output.UnlockBits(bmpData);
        return output;
    }
}

This is a slightly variation of a solution which was posted on this site.

isaias-b
  • 2,255
  • 2
  • 25
  • 38
  • as a reference MSDN: Bitmap(Int32, Int32): "This constructor creates a Bitmap with a PixelFormat enumeration value of Format32bppArgb.", which means byte[0] is blue, byte[1] is green, byte[2] is red, byte[3] is alpha, byte[4] is blue, and so on. – kbridge4096 Jan 13 '18 at 17:25
  • 3
    THANK YOU for adding all of the needed "using"s. Most people forget that and it an be a pain to find them all. – Casey Crookston May 01 '18 at 22:06
  • 1
    boy did you save me man, thanks! – Vulovic Vukasin Sep 02 '22 at 14:28
7

In one line:

Image.FromStream(new MemoryStream(byteArrayIn));
TiyebM
  • 2,684
  • 3
  • 40
  • 66
6

there is a simple approach as below, you can use FromStream method of an image to do the trick, Just remember to use System.Drawing;

// using image object not file 
public byte[] imageToByteArray(Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}
demo
  • 6,038
  • 19
  • 75
  • 149
Ali
  • 1,080
  • 16
  • 22
6

try (UPDATE)

MemoryStream ms = new MemoryStream(byteArrayIn,0,byteArrayIn.Length);
ms.Position = 0; // this is important
returnImage = Image.FromStream(ms,true);
Yahia
  • 69,653
  • 9
  • 115
  • 144
  • 2
    It makes little sense to write the byte array to the memory stream after it has been initialized with the same byte array. Actually I am not sure MemoryStream allows writing beyond the length specified in the constructor. – Holstebroe Feb 07 '12 at 09:53
3

One liner:

Image bmp = (Bitmap)((new ImageConverter()).ConvertFrom(imageBytes));
Vinnie Amir
  • 557
  • 5
  • 10
2

This is inspired by Holstebroe's answer, plus comments here: Getting an Image object from a byte array

Bitmap newBitmap;
using (MemoryStream memoryStream = new MemoryStream(byteArrayIn))
    using (Image newImage = Image.FromStream(memoryStream))
        newBitmap = new Bitmap(newImage);
return newBitmap;
Community
  • 1
  • 1
RenniePet
  • 11,420
  • 7
  • 80
  • 106
2

You haven't declared returnImage as any kind of variable :)

This should help:

public Image byteArrayToImage(byte[] byteArrayIn)
{
    try
    {
        MemoryStream ms = new MemoryStream(byteArrayIn,0,byteArrayIn.Length);
        ms.Write(byteArrayIn, 0, byteArrayIn.Length);
        Image returnImage = Image.FromStream(ms,true);
    }
    catch { }
    return returnImage;
}
LeeCambl
  • 376
  • 4
  • 15
  • 1
    Code useful as an idea, but of course won't work as written. returnImage has to be declared outside of try/catch section. Also returnImage has to be instantiated in 'catch' - I create a single pixel bitmap: var image = new Bitmap(1, 1); MemoryStream stream = new MemoryStream(); image.Save(stream, ImageFormat.Jpeg); stream.Position = 0; – Reid Jun 11 '17 at 19:33
1

Most of the time when this happens it is bad data in the SQL column. This is the proper way to insert into an image column:

INSERT INTO [TableX] (ImgColumn) VALUES (
(SELECT * FROM OPENROWSET(BULK N'C:\....\Picture 010.png', SINGLE_BLOB) as tempimg))

Most people do it incorrectly this way:

INSERT INTO [TableX] (ImgColumn) VALUES ('C:\....\Picture 010.png'))
GPGVM
  • 5,515
  • 10
  • 56
  • 97
0

First Install This Package:

Install-Package SixLabors.ImageSharp -Version 1.0.0-beta0007

[SixLabors.ImageSharp][1] [1]: https://www.nuget.org/packages/SixLabors.ImageSharp

Then use Below Code For Cast Byte Array To Image :

Image<Rgba32> image = Image.Load(byteArray); 

For Get ImageFormat Use Below Code:

IImageFormat format = Image.DetectFormat(byteArray);

For Mutate Image Use Below Code:

image.Mutate(x => x.Resize(new Size(1280, 960)));
Amin Golmahalleh
  • 3,585
  • 2
  • 23
  • 36
0

I suggest using ImageSharp

Image<Bgra32> image = SixLabors.ImageSharp.Image.LoadPixelData<Bgra32>
                        (byteArray
                        , pageWidth
                        , pageHeight);
D.Oleg
  • 71
  • 1
  • 3