多页tiff转jpg
最近好几个站友求这段代码,就放这里,免得每次发邮件了。import java.awt.image.RenderedImage;import java.io.*;import com.sun.media.jai.codec.*;/*** @version 1.0 2008-1-14 12:09:10*/public class TiffUtil{ public static final String TIFF = "TIFF"; public static final String JPEG = "JPEG"; public static int getTotalPageNumber(File file) throws IOException { SeekableStream seekableStream = new FileSeekableStream(file); TIFFDecodeParam param = new TIFFDecodeParam(); ImageDecoder dec = ImageCodec.createImageDecoder(TIFF, seekableStream, param); return dec.getNumPages(); } /** * 获取tiff文件中的某页的图像,页号从0开始 * * @param tiffInputStream tiff输入流 * @param pageNum tiff文件中的某页号,从0开始 * @return tiff中的某页图象 * @throws IOException; */ public static RenderedImage getSinglePageRenderImage(InputStream tiffInputStream, int pageNum) throws IOException { int page = pageNum - 1; TIFFDecodeParam param = new TIFFDecodeParam(); ImageDecoder dec = ImageCodec.createImageDecoder(TIFF, tiffInputStream, param); int numPages = dec.getNumPages(); if (page < 0 || page >= numPages) { throw new IndexOutOfBoundsException(); } return dec.decodeAsRenderedImage(page); } /** * 获取tiff文件中的某页的图像,页号从0开始 * * @param file tiff文件 * @param pageNum tiff文件中的某页号,从0开始 * @return tiff中的某页图象 * @throws IOException; */ public static RenderedImage getSinglePageRenderImage(File file, int pageNum) throws IOException { int page = pageNum - 1; TIFFDecodeParam param = new TIFFDecodeParam(); ImageDecoder dec = ImageCodec.createImageDecoder(TIFF, file, param); int numPages = dec.getNumPages(); if (page < 0 || page >= numPages) { throw new IndexOutOfBoundsException(); } return dec.decodeAsRenderedImage(page); } public static void main(String[] args) throws IOException { File file = new File("n:/tmp/a.tiff"); RenderedImage image = TiffUtil.getSinglePageRenderImage(file, 1); JPEGEncodeParam param = new JPEGEncodeParam(); param.setQuality(0.075f); try { OutputStream os = new FileOutputStream("n:/tmp/a.jpg"); ImageEncoder imageEncoder = ImageCodec.createImageEncoder(JPEG, os, param); imageEncoder.encode(image); os.close(); } catch (Exception e) { e.printStackTrace(); } }}
页:
[1]