Extract frame from multi page tiff - 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.
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();
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);
}
}
}
Using ImageMagick, extracting pages is a simple one-liner:
convert input.tif[page] output.tif
To extract a range of pages, replace [page]
with [frompage-topage]
. It's important to note that page count start from zero.
In your case, you'd have to run the command twice, but ImageMagick is so powerful I bet there is another one-line command that does the split just the way you want.
Never used C#, so I don't know whether or not this can be used inside your code.
精彩评论