Question

Hi I can’t find sample for convert MULTI PAGE tiff image to byte array.

For convert byte array to Tiff I use this method

    public static Tiff CreateTiffFromBytes(byte[] bytes)
    {
        using (var ms = new MemoryStream(bytes))
        {
            Tiff tiff = Tiff.ClientOpen("in-memory", "r", ms, new TiffStream());
            return tiff;
        }
    }

EDITED:

This method convert TIFF image with more pages to byte Array. I think in this method will be root of problem.

    //imageIn is tif image with 12 pages
    public static byte[] ImageToByteArray(System.Drawing.Image imageIn)
    {       
        using (var ms = new MemoryStream())
        {
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff);
            return ms.ToArray();
        }
    }

   public static List<System.Drawing.Image> GetAllPages(System.Drawing.Image multiTiff)
    {
        var images = new List<System.Drawing.Image>();
        var bitmap = (Bitmap)multiTiff;
        int count = bitmap.GetFrameCount(FrameDimension.Page);

        for (int idx = 0; idx < count; idx++)
        {
            bitmap.SelectActiveFrame(FrameDimension.Page, idx);
            using (var byteStream = new MemoryStream())
            {
                bitmap.Save(byteStream, ImageFormat.Tiff);

                images.Add(System.Drawing.Image.FromStream(byteStream));
            }
        }
        return images;
    }

After conversion to byte array I lose pages. Image from byte array has only one page.

  Image src = Image.FromFile(source);
    //imagesInSource.Count (pages) is 12
    List<Image> imagesInSource = GetAllPages(src);

    byte[] imageData = ImageToByteArray(src);

    Image  des = ImageConvert.ByteArrayToImage(imageData);
    //imagesInSource.Count (pages) is 1
    List<Image> imagesInDes = GetAllPages(des);
Was it helpful?

Solution

I am not sure why you can't send TIFF file to the service? The file is just bytes, after all.

And your code in the first snippet is incorrect because you dispose memory stream that is passed to Tiff object. You shouldn't do that. The Tiff object will dispose the stream itself.

EDIT:

In the third snippet you create images for each page of the System.Drawing.Image but the you convert only first produced image to byte array. You should use something like

List<byte[]> imagesBytes = new List<byte[]>();
foreach (Image img in imagesInSource)
{
    byte[] imageData = ImageToByteArray(src);
    imageBytes.Add(imageData);
}

Then you should send imagesBytes to your server and create several TIFF images from that.

Anyway, it seems like you should think more about what are you really trying to do. Because for now it unclear to me what all these conversions are for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top