Hairy Dresden
Hairy Dresden

Reputation: 160

Importing a multipage .tif to bitmap in C#

I am trying to open a .tiff file with 12 pages. I will then perform some math on individual pixels and then spit it back out. How can I import it and then split it? I am trying to make it import to a bitmap array. I declare the array at the beginning:

Bitmap[] tifBitmap = new Bitmap[10];

And then I want to write a value to each in this method:

private void splitTiff(String location)
    {
        int activePage;
        int pages;

        System.Drawing.Image image = System.Drawing.Image.FromFile(location);

        pages = image.GetFrameCount(FrameDimension.Page);



        for (int i = 0; i < 12; i++)
        {
            activePage = i + 1;

            image.SelectActiveFrame(FrameDimension.Page, i);

            //this is what I need to figure out
            tifBitmap[i - 1] = [save image slice here somehow];


        }
    }

Now I know that this code is a mess, but it shows the idea. How would I be able pull this off?

Upvotes: 1

Views: 3423

Answers (1)

Kevin
Kevin

Reputation: 2243

Okay, I took on this problem because it's relevant to my occupation (I'm an Imaging DBA) and because I didn't know the answer.

Anyway, here's what I found (which may or may not be the optimal answer, but it seems to work)

You're on the right track with the SelectActiveFrame bit, but what I think you need to do is:

  1. Create a MemoryStream
  2. Save the Image to the MemoryStream with a .BMP format
  3. Create a Bitmap object that loads from the MemoryStream

Here's my sample code:

Image sampleTiffImage = Image.FromFile(@"C:\SomeExample.tif");

int pageCount = sampleTiffImage.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);


for (int pageNum = 0; pageNum < pageCount; pageNum++)
{
    sampleTiffImage.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, pageNum);

    using (MemoryStream memStream = new MemoryStream())
    {
        sampleTiffImage.Save(memStream, ImageFormat.Bmp);
        using (Bitmap myBitmap = (Bitmap)Bitmap.FromStream(memStream))
        {
            myBitmap.Save(@"C:\someFol\" + pageNum + ".bmp");
            // note: the above line is saving to disk.  I'm doing it for testing purposes,
            // but you're going to want to copy it to your array.
        }
    }
}

I'm saving out the files, but you're going to want to load them into your array instead.

Hope that helps!

Upvotes: 2

Related Questions