Search code examples
javascriptnode.jsmetadatatiffsharp

multi pages tiff format node js


I have a file image.tiff with 3 pages. I want to save each page in separate file in fs. I tried to use a sharp library to extract each page and to save it. I got from metadate height, width, and number of pages, so I could calculate the position for crop area. but when I checked the height, I find that I got only the singe page height, not a total height of all the pages (which I hoped to get), so I get only the top part of the first page. not cool. any ideas how to crop each page separately? or any other solution for my problem. thanks!

const image = sharp(filePath);

image
    .metadata()
    .then(function (metadata: any) {
        splitPages(metadata.width, metadata.height, metadata.pages);
        return image
     
    });


function splitPages(width: number, heigth: number, pagesNum: number): void {

const page_heigth = heigth / pagesNum;
const left = 0;
const top_positions: number[] = [];
let top = 0;
for (let i = 0; i < pagesNum; i++) {
    top = (pagesNum *heigth) - ((i + 1) * page_heigth);
    top_positions.push(top);
}
top_positions.reverse();
top_positions.map((top, i)=>{
    const top_position = top;
       image.extract({ left: left, top: top_position, width: width, height: page_heigth })
       .toFile(`C:\\sample_${i}.tiff`);

})

}


Solution

  • Your first line of code, where you use sharp's ctor factory, should provide the option to allow extraction of multiple pages.

    const image = sharp(filePath, {pages:-1} );