Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract frame from multi page tiff - c#

Tags:

c#

Have a multi page tiff and I want to extract page[n]/frame[n] from this Tiff file and save it.

If my multi page tiff has 3 frames, after I extract one page/frame - I want to be left with

1 image having 2 pages/frames and

1 image having only 1 page/frame.

like image 911
uno Avatar asked Aug 03 '10 17:08

uno


People also ask

How do I split a multi page TIFF?

First, you need to add a file for split: drag & drop your TIFF file or click inside the white area for choose a file. Then click the 'Split' button. When split TIFF document is completed, you can download your result files.

Can a TIFF have multiple pages?

Yes, a TIFF file can have multiple pages. A multipage TIFF file saves multiple pages as individual image frames. However, mostly the TIFF images are saved one page per file.


2 Answers

Here is some code to save the last Frame in a multi-frame tiff to a single page tiff file. (In order to use this code you need to add a reference to the PresentationCore.dll).

Stream imageStreamSource = new FileStream(imageFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
        MemoryStream memstream = new MemoryStream();
        memstream.SetLength(imageStreamSource.Length);
        imageStreamSource.Read(memstream.GetBuffer(), 0, (int)imageStreamSource.Length);
        imageStreamSource.Close();

        BitmapDecoder decoder = TiffBitmapDecoder.Create(memstream,BitmapCreateOptions.PreservePixelFormat,BitmapCacheOption.Default);

        Int32 frameCount = decoder.Frames.Count;

        BitmapFrame imageFrame = decoder.Frames[0];

        MemoryStream output = new MemoryStream();
        TiffBitmapEncoder encoder = new TiffBitmapEncoder();
        encoder.Frames.Add(imageFrame);
        encoder.Save(output);

        FileStream outStream = File.OpenWrite("Image.Tiff");
        output.WriteTo(outStream);
        outStream.Flush();
        outStream.Close();
        output.Flush();
        output.Close();
like image 115
Gary Kindel Avatar answered Oct 02 '22 04:10

Gary Kindel


    public void SaveFrame(string path, int frameIndex, string toPath)
    {
        using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            BitmapDecoder dec = BitmapDecoder.Create(stream, BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.None);
            BitmapEncoder enc = BitmapEncoder.Create(dec.CodecInfo.ContainerFormat);

            enc.Frames.Add(dec.Frames[frameIndex]);

            using (FileStream tmpStream = new FileStream(toPath, FileMode.Create))
            {
                enc.Save(tmpStream);
            }
        }
    }
like image 45
Jose Avatar answered Oct 02 '22 05:10

Jose