Search code examples
c#arraysimage-processingmemorystream

Converting byte array to image in C#


I have converted an image(.tif image) to a byte array and saved in the DB. I am now retrieving that byte array from the DB and want to convert to an image again, but this byte array I am converting back to an image, is not producing the same. As a test (as below), I am only using the image and not reading from the DB, for testing purposes.

The initial convert from Image to byte array:

//This is the function I am using:
public static byte[] ImageToByteArray(Image image)
        {
            using (var ms = new MemoryStream())
            {
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff);
                return ms.ToArray();
            }
        }

//Converting to byte array:
var tifImage = Image.FromFile(file.ToString());
var imageContent = ImageToByteArray(tifImage);

Now to try and convert back to an Image, I am doing the following:

var ms = new MemoryStream(imageContent);
var test1 = Image.FromStream(ms);

But it seems the results are not the same. I have a "Splitting" function that splits the pages within the tiff, and the one returns 8 pages(bitmaps) and the other just 1.

I dont know much about the above, so need a little help in filling in the knowledge gaps, please :)

Thanks for any the help!


Solution

  • I found a solution that ended up working. It seems that when the initial ImageToByteArray was being done, it was only doing the "1st page" and not all 8. So I used the following code to convert the whole tiff image:

    var tiffArray = File.ReadAllBytes(file); //The `file` is the actual `.tiff` file
    

    I then used the following to convert back to an image(The response is a byte[] returned from our API):

    using (MemoryStream ms = new MemoryStream(response))
                {
                    ms.Position = 0;
                    Image returnImage = Image.FromStream(ms);
    
                    var splitImages = ImageHelper.Split(returnImage);//This is to split the pages within the tiff
                }
    

    I read that for the above to work(and I tested it), anything you do to the byte[]you are converting back to an image, must be done within the using, as anything after the using means the image is disposed.