Java Code Examples for javax.imageio.ImageIO#getImageReadersByFormatName()
The following examples show how to use
javax.imageio.ImageIO#getImageReadersByFormatName() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImageUtils.java From springboot-admin with Apache License 2.0 | 6 votes |
/** * 等比缩放,居中剪切 * * @param src * @param dest * @param w * @param h * @throws IOException */ public static void scale(String src, String dest, int w, int h) throws IOException { String srcSuffix = src.substring(src.lastIndexOf(".") + 1); Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName(srcSuffix); ImageReader reader = (ImageReader) iterator.next(); InputStream in = new FileInputStream(src); ImageInputStream iis = ImageIO.createImageInputStream(in); reader.setInput(iis); BufferedImage srcBuffered = readBuffereImage(reader, w, h); BufferedImage targetBuffered = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics graphics = targetBuffered.getGraphics(); graphics.drawImage(srcBuffered.getScaledInstance(w, h, Image.SCALE_DEFAULT), 0, 0, null); // 绘制缩小后的图 graphics.dispose(); srcBuffered.flush(); in.close(); iis.close(); ImageIO.write(targetBuffered, srcSuffix, new File(dest)); targetBuffered.flush(); }
Example 2
Source File: ImageUtils.java From albert with MIT License | 6 votes |
/** * 使用ImageReader获取图片尺寸 * * @param src 源图片路径 */ public void getImageSizeByImageReader(String src) { long beginTime = new Date().getTime(); File file = new File(src); try { Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg"); ImageReader reader = (ImageReader) readers.next(); ImageInputStream iis = ImageIO.createImageInputStream(file); reader.setInput(iis, true); System.out.println("width:" + reader.getWidth(0)); System.out.println("height:" + reader.getHeight(0)); } catch (IOException e) { logger.error("ImageUtils.getImageSizeByImageReader", e); } long endTime = new Date().getTime(); System.out.println("使用[ImageReader]获取图片尺寸耗时:[" + (endTime - beginTime)+"]ms"); }
Example 3
Source File: JPEGFactory.java From sambox with Apache License 2.0 | 6 votes |
private static BufferedImage readJpeg(Object fileOrStream) throws IOException { Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("JPEG"); ImageReader reader = null; while (readers.hasNext()) { reader = readers.next(); if (reader.canReadRaster()) { break; } } requireIOCondition(nonNull(reader), "Cannot find an ImageIO reader for JPEG image"); try (ImageInputStream iis = ImageIO.createImageInputStream(fileOrStream)) { reader.setInput(iis); ImageIO.setUseCache(false); return reader.read(0); } finally { reader.dispose(); } }
Example 4
Source File: Filter.java From gcs with Mozilla Public License 2.0 | 6 votes |
/** * Finds a suitable image reader for a format. * * @param formatName The format to search for. * @param errorCause The probably cause if something goes wrong. * @return The image reader for the format. * @throws MissingImageReaderException if no image reader is found. */ protected static ImageReader findImageReader(String formatName, String errorCause) throws MissingImageReaderException { Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(formatName); ImageReader reader = null; while (readers.hasNext()) { reader = readers.next(); if (reader != null && reader.canReadRaster()) { break; } } if (reader == null) { throw new MissingImageReaderException("Cannot read " + formatName + " image: " + errorCause); } return reader; }
Example 5
Source File: ImageUtils.java From jpress with GNU Lesser General Public License v3.0 | 6 votes |
/** * 等比缩放,居中剪切 * * @param src * @param dest * @param w * @param h * @throws IOException */ public static void scale(String src, String dest, int w, int h) throws IOException { if (notImageExtName(src)) { throw new IllegalArgumentException("只支持如下几种图片格式:jpg、jpeg、png、bmp"); } Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName(getExtName(src)); ImageReader reader = (ImageReader) iterator.next(); InputStream in = new FileInputStream(src); ImageInputStream iis = ImageIO.createImageInputStream(in); reader.setInput(iis); BufferedImage srcBuffered = readBuffereImage(reader, w, h); BufferedImage targetBuffered = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics graphics = targetBuffered.getGraphics(); graphics.drawImage(srcBuffered.getScaledInstance(w, h, Image.SCALE_DEFAULT), 0, 0, null); // 绘制缩小后的图 graphics.dispose(); srcBuffered.flush(); save(targetBuffered, dest); targetBuffered.flush(); }
Example 6
Source File: DbxClientV1IT.java From dropbox-sdk-java with MIT License | 5 votes |
private static ImageReader getImageReaderForFormat(DbxThumbnailFormat format) { Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(format.ident); if (!readers.hasNext()) { throw new AssertionError("no ImageReader for " + jq(format.ident)); } ImageReader reader = readers.next(); if (readers.hasNext()) { throw new AssertionError("multiple ImageReaders for " + jq(format.ident)); } return reader; }
Example 7
Source File: BMPPluginTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private static void init() { Iterator i = ImageIO.getImageWritersByFormatName(format); if (!i.hasNext()) { throw new RuntimeException("No available ImageWrites for "+format+" format!"); } iw = (ImageWriter)i.next(); i = ImageIO.getImageReadersByFormatName(format); if (!i.hasNext()) { throw new RuntimeException("No available ImageReaders for " +format+" format!"); } ir = (ImageReader)i.next(); }
Example 8
Source File: OCRUtil.java From JewelCrawler with GNU General Public License v3.0 | 5 votes |
public static File createImage(File imageFile, String imageFormat) { File tempFile = null; try { Iterator<ImageReader> readers = ImageIO .getImageReadersByFormatName(imageFormat); ImageReader reader = readers.next(); ImageInputStream iis = ImageIO.createImageInputStream(imageFile); reader.setInput(iis); // Read the stream metadata IIOMetadata streamMetadata = reader.getStreamMetadata(); // Set up the writeParam TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam( Locale.US); tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED); // Get tif writer and set output to file Iterator<ImageWriter> writers = ImageIO .getImageWritersByFormatName("tiff"); ImageWriter writer = writers.next(); BufferedImage bi = reader.read(0); // bi = new ImageFilter(bi).changeGrey(); IIOImage image = new IIOImage(bi, null, reader.getImageMetadata(0)); tempFile = tempImageFile(imageFile); ImageOutputStream ios = ImageIO.createImageOutputStream(tempFile); writer.setOutput(ios); writer.write(streamMetadata, image, tiffWriteParam); ios.close(); writer.dispose(); reader.dispose(); } catch (Exception exc) { exc.printStackTrace(); } return tempFile; }
Example 9
Source File: GetReaderWriterInfo.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private static void testGetReaderFormatNames() { String[] names = ImageIO.getReaderFormatNames(); for (String n : names) { Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(n); if (!it.hasNext()) { throw new RuntimeException("getReaderFormatNames returned " + "an unknown name: " + n); } } }
Example 10
Source File: GetReaderWriterInfo.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
private static void testGetReaderFormatNames() { String[] names = ImageIO.getReaderFormatNames(); for (String n : names) { Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(n); if (!it.hasNext()) { throw new RuntimeException("getReaderFormatNames returned " + "an unknown name: " + n); } } }
Example 11
Source File: ImageIOHelper.java From JewelCrawler with GNU General Public License v3.0 | 5 votes |
public static BufferedImage getImage(File imageFile) { BufferedImage al = null; try { String imageFileName = imageFile.getName(); String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1); Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat); ImageReader reader = readers.next(); if (reader == null) { JOptionPane.showConfirmDialog(null, "Need to install JAI Image I/O package.\nhttps://jai-imageio.dev.java.net"); return null; } ImageInputStream iis = ImageIO.createImageInputStream(imageFile); reader.setInput(iis); al = reader.read(0); reader.dispose(); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } catch (Exception e) { System.err.println(e.getMessage()); } return al; }
Example 12
Source File: ImageIOHelper.java From tess4j with Apache License 2.0 | 5 votes |
/** * Gets a list of <code>IIOImage</code> objects for an image file. * * @param inputFile input image file. It can be any of the supported * formats, including TIFF, JPEG, GIF, PNG, BMP, JPEG, and PDF if GPL * Ghostscript or PDFBox is installed * @return a list of <code>IIOImage</code> objects * @throws IOException */ public static List<IIOImage> getIIOImageList(File inputFile) throws IOException { // convert to TIFF if PDF File imageFile = getImageFile(inputFile); List<IIOImage> iioImageList = new ArrayList<IIOImage>(); String imageFormat = getImageFileFormat(imageFile); Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat); if (!readers.hasNext()) { throw new RuntimeException(JAI_IMAGE_READER_MESSAGE); } ImageReader reader = readers.next(); try (ImageInputStream iis = ImageIO.createImageInputStream(imageFile)) { reader.setInput(iis); int imageTotal = reader.getNumImages(true); for (int i = 0; i < imageTotal; i++) { // IIOImage oimage = new IIOImage(reader.read(i), null, reader.getImageMetadata(i)); IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam()); iioImageList.add(oimage); } return iioImageList; } finally { if (reader != null) { reader.dispose(); } // delete temporary TIFF image for PDF if (imageFile != null && imageFile.exists() && imageFile != inputFile && imageFile.getName().startsWith("multipage") && imageFile.getName().endsWith(TIFF_EXT)) { imageFile.delete(); } } }
Example 13
Source File: BMPPluginTest.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
private static void init() { Iterator i = ImageIO.getImageWritersByFormatName(format); if (!i.hasNext()) { throw new RuntimeException("No available ImageWrites for "+format+" format!"); } iw = (ImageWriter)i.next(); i = ImageIO.getImageReadersByFormatName(format); if (!i.hasNext()) { throw new RuntimeException("No available ImageReaders for " +format+" format!"); } ir = (ImageReader)i.next(); }
Example 14
Source File: ImageIOHelper.java From tess4j with Apache License 2.0 | 5 votes |
/** * Gets a list of <code>BufferedImage</code> objects for an image file. * * @param inputFile input image file. It can be any of the supported * formats, including TIFF, JPEG, GIF, PNG, BMP, JPEG, and PDF if GPL * Ghostscript or PDFBox is installed * @return a list of <code>BufferedImage</code> objects * @throws IOException */ public static List<BufferedImage> getImageList(File inputFile) throws IOException { // convert to TIFF if PDF File imageFile = getImageFile(inputFile); List<BufferedImage> biList = new ArrayList<BufferedImage>(); String imageFormat = getImageFileFormat(imageFile); Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat); if (!readers.hasNext()) { throw new RuntimeException(JAI_IMAGE_READER_MESSAGE); } ImageReader reader = readers.next(); try (ImageInputStream iis = ImageIO.createImageInputStream(imageFile)) { reader.setInput(iis); int imageTotal = reader.getNumImages(true); for (int i = 0; i < imageTotal; i++) { BufferedImage bi = reader.read(i); biList.add(bi); } return biList; } finally { if (reader != null) { reader.dispose(); } // delete temporary TIFF image for PDF if (imageFile != null && imageFile.exists() && imageFile != inputFile && imageFile.getName().startsWith("multipage") && imageFile.getName().endsWith(TIFF_EXT)) { imageFile.delete(); } } }
Example 15
Source File: ImageResizeAndCompression.java From o2oa with GNU Affero General Public License v3.0 | 4 votes |
public static BufferedImage cut( BufferedImage src, Integer width, Integer height ) throws IOException { int old_w = src.getWidth(); //得到源图宽 int old_h = src.getHeight(); //得到源图高 int new_w = width; int new_h = height; BufferedImage tempImg = new BufferedImage( old_w, old_h, BufferedImage.TYPE_INT_RGB ); Graphics2D g = tempImg.createGraphics(); g.setColor( Color.white ); // 从原图上取颜色绘制新图 g.fillRect(0, 0, old_w, old_h); g.drawImage( src, 0, 0, old_w, old_h, Color.white, null ); g.dispose(); // 根据图片尺寸压缩比得到新图的尺寸 if( ( old_w*1.0 )/new_w < ( new_h*1.0 )/new_h ){//纵向缩放比例大 if( old_w > new_w ){//实际的图片宽度,大于预期的缩放宽度,需要进行高度按比例缩小 new_h = Integer.parseInt( new java.text.DecimalFormat("0").format(old_h * new_w/(old_w*1.0)) ); } } else {//横向绽放比例大 if(old_h > new_h){ new_w = Integer.parseInt(new java.text.DecimalFormat("0").format(old_w * new_h/(old_h*1.0))); } } BufferedImage newImg = new BufferedImage( new_w, new_h, BufferedImage.TYPE_INT_RGB); newImg.getGraphics().drawImage( tempImg.getScaledInstance( new_w, new_h, Image.SCALE_SMOOTH), 0, 0, null ); //准备进行裁剪 ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 调用方法输出图片文件 outImage( baos, newImg, 1 ); ByteArrayInputStream is = new ByteArrayInputStream(baos.toByteArray()); ImageInputStream iis = null; try { /* * 返回包含所有当前已注册 ImageReader 的 Iterator,这些 ImageReader 声称能够解码指定格式。 * 参数:formatName - 包含非正式格式名称 .(例如 "jpeg" 或 "tiff")等 。 */ Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpg"); ImageReader reader = it.next(); // 获取图片流 iis = ImageIO.createImageInputStream(is); /* * <p>iis:读取源.true:只向前搜索 </p>.将它标记为 ‘只向前搜索’。 * 此设置意味着包含在输入源中的图像将只按顺序读取,可能允许 reader 避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。 */ reader.setInput(iis, true); /* * <p>描述如何对流进行解码的类<p>.用于指定如何在输入时从 Java Image I/O * 框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件 将从其 ImageReader 实现的 * getDefaultReadParam 方法中返回 ImageReadParam 的实例。 */ ImageReadParam param = reader.getDefaultReadParam(); /* * 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域,通过 Rectangle 对象 * 的左上顶点的坐标(x,y)、宽度和高度可以定义这个区域。 */ int x=0, y=0; if( new_w > width ){ //水平中间截取 x = ( new_w-width )/2; }else{ y = ( new_h-height )/2; } Rectangle rect = new Rectangle( x, y, width, height); // 提供一个 BufferedImage,将其用作解码像素数据的目标。 param.setSourceRegion(rect); /* * 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象,并将 它作为一个完整的 * BufferedImage 返回。 */ BufferedImage bi = reader.read(0, param); // 保存新图片 return bi; } finally { if (is != null) { is.close(); } if (iis != null) { iis.close(); } } }
Example 16
Source File: ToolImageTailor.java From protools with Apache License 2.0 | 4 votes |
/** * 裁剪 * * @param srcPath * 源图片路径名称如:c:/1.jpg * @param savePath * 剪切图片存放路径名称.如:c:/2.jpg * @param x * 剪切点x坐标 * @param y * @param width * 剪切点大小 * @param height * * @throws IOException */ public static void cut(String srcPath, String savePath, int x, int y, int width, int height) throws IOException { String endWiths = srcPath.substring(srcPath.lastIndexOf(".") + 1);// 后缀 /* * 返回包含所有当前已注册 ImageReader 的 Iterator,这些 ImageReader 声称能够解码指定格式。 参数:formatName - 包含非正式格式名称 .(例如 "jpeg" 或 "tiff")等 。 */ Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpg"); ImageReader reader = it.next(); try ( // 读取图片文件 FileInputStream is = new FileInputStream(srcPath); // 获取图片流 ImageInputStream iis = ImageIO.createImageInputStream(is) ) { /* * <p>iis:读取源.true:只向前搜索 </p>.将它标记为 ‘只向前搜索’。 此设置意味着包含在输入源中的图像将只按顺序读取,可能允许 reader 避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。 */ reader.setInput(iis, true); /* * <p>描述如何对流进行解码的类<p>.用于指定如何在输入时从 Java Image I/O 框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件 将从其 ImageReader 实现的 getDefaultReadParam 方法中返回 * ImageReadParam 的实例。 */ ImageReadParam param = reader.getDefaultReadParam(); /* * 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域,通过 Rectangle 对象 的左上顶点的坐标(x,y)、宽度和高度可以定义这个区域。 */ Rectangle rect = new Rectangle(x, y, width, height); // 提供一个 BufferedImage,将其用作解码像素数据的目标。 param.setSourceRegion(rect); /* * 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象,并将 它作为一个完整的 BufferedImage 返回。 */ BufferedImage bi = reader.read(0, param); // 保存新图片 ImageIO.write(bi, endWiths, new File(savePath)); // "jpg" } }
Example 17
Source File: ImageIOHelper.java From tess4j with Apache License 2.0 | 4 votes |
/** * Merges multiple images into one multi-page TIFF image. * * @param inputImages an array of image files * @param outputTiff the output multi-page TIFF file * @throws IOException */ public static void mergeTiff(File[] inputImages, File outputTiff) throws IOException { if (inputImages.length == 0) { // if no image return; } Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT); if (!writers.hasNext()) { throw new RuntimeException(JAI_IMAGE_WRITER_MESSAGE); } ImageWriter writer = writers.next(); //Set up the writeParam TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US); // tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED); // commented out to preserve original sizes //Get the stream metadata IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam); try (ImageOutputStream ios = ImageIO.createImageOutputStream(outputTiff)) { writer.setOutput(ios); boolean firstPage = true; int index = 1; for (File inputImage : inputImages) { String imageFileFormat = getImageFileFormat(inputImage); Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFileFormat); if (!readers.hasNext()) { throw new RuntimeException(JAI_IMAGE_READER_MESSAGE); } ImageReader reader = readers.next(); try (ImageInputStream iis = ImageIO.createImageInputStream(inputImage)) { reader.setInput(iis); int imageTotal = reader.getNumImages(true); for (int i = 0; i < imageTotal; i++) { IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam()); if (firstPage) { writer.write(streamMetadata, oimage, tiffWriteParam); firstPage = false; } else { writer.writeInsert(index++, oimage, tiffWriteParam); } } } finally { if (reader != null) { reader.dispose(); } } } } finally { writer.dispose(); } }
Example 18
Source File: ImageUtils.java From albert with MIT License | 4 votes |
/*** * 缩放图像,按照长宽缩放 * @param srcImageFile * @param result * @param height 变换后的高度 * @param width 变换后的长度 * @param bb 比例不对称时,是否补白,true 补白;false 不补白 * @return * @date 2016-3-30下午2:44:37 */ public static boolean scale2(String srcImageFile, String result, int height, int width, boolean bb) { try { double ratio = 0.0; // 缩放比例 File file = new File(srcImageFile); BufferedImage bi = ImageIO.read(file); // 读入文件 Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg"); ImageReader reader = (ImageReader) readers.next(); ImageInputStream iis = ImageIO.createImageInputStream(file); reader.setInput(iis, true); int width1 = reader.getWidth(0); // 得到源图宽 int height1 = reader.getHeight(0); // 得到源图长 @SuppressWarnings("static-access") Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH); // 计算比例 if ((height1 > height) || (width1 > width)) { if (height1 > width1) { ratio = (new Integer(height)).doubleValue() / height1; } else { ratio = (new Integer(width)).doubleValue() / width1; } AffineTransformOp op = new AffineTransformOp(AffineTransform .getScaleInstance(ratio, ratio), null); itemp = op.filter(bi, null); } if (bb) {//补白 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.setColor(Color.white); g.fillRect(0, 0, width, height); if (width == itemp.getWidth(null)) g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), Color.white, null); else g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), Color.white, null); g.dispose(); itemp = image; } ImageIO.write((BufferedImage) itemp, "JPEG", new File(result)); return true; } catch (IOException e) { e.printStackTrace(); return false; } }
Example 19
Source File: ImageUtils.java From albert with MIT License | 4 votes |
/** * 剪裁图片(x,y,w,h,r) * @param srcImageFile 文件流:源图像地址 * @param dest 新图像 * @param x 目标切片起点x坐标 * @param y 目标切片起点y坐标 * @param w 目标切片宽度 * @param h 目标切片高度 * @param r 目标切片旋转度 * @return */ public static boolean cutAndRotateImage(InputStream srcImageFile,File dest,int x,int y,int w,int h,int r){ try{ /* * BufferedImage是Image的一个子类,BufferedImage生成的图片在内存里有一个图像缓冲区, * 利用这个缓冲区我们可以很方便的操作这个图片,通常用来做图片修改操作如大小变换、图片变灰、设置图片透明或不透明等。 */ BufferedImage src = ImageIO.read(srcImageFile); // 读入文件 //图片旋转指定角度 BufferedImage tag= Rotate(src, r); //读取图片文件 Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName("jpg"); ImageReader reader = (ImageReader)iterator.next(); //获取图片流 ByteArrayOutputStream bs = new ByteArrayOutputStream(); ImageOutputStream ios = ImageIO.createImageOutputStream(bs); ImageIO.write(tag, "jpg", ios); InputStream in=new ByteArrayInputStream(bs.toByteArray()); ImageInputStream iis=ImageIO.createImageInputStream(in); reader.setInput(iis, true); ImageReadParam param = reader.getDefaultReadParam(); x=(x>0?x:0); y=(y>0?y:0); //定义一个矩形 Rectangle rect = new Rectangle(x, y, w,h); //提供一个 BufferedImage,将其用作解码像素数据的目标。 param.setSourceRegion(rect); BufferedImage bi = reader.read(0,param); //保存新图片 ImageIO.write(bi, "jpg", dest); return true; }catch (Exception e) { return false; } }
Example 20
Source File: ImageIOHelper.java From tess4j with Apache License 2.0 | 4 votes |
/** * Creates a list of TIFF image files from an image file. It basically * converts images of other formats to TIFF format, or a multi-page TIFF * image to multiple TIFF image files. * * @param imageFile input image file * @param index an index of the page; -1 means all pages, as in a multi-page * TIFF image * @param preserve preserve compression mode * @return a list of TIFF image files * @throws IOException */ public static List<File> createTiffFiles(File imageFile, int index, boolean preserve) throws IOException { List<File> tiffFiles = new ArrayList<File>(); String imageFormat = getImageFileFormat(imageFile); Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat); if (!readers.hasNext()) { throw new RuntimeException(JAI_IMAGE_READER_MESSAGE); } ImageReader reader = readers.next(); // Get tiff writer and set output to file Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT); if (!writers.hasNext()) { throw new RuntimeException(JAI_IMAGE_WRITER_MESSAGE); } ImageWriter writer = writers.next(); try (ImageInputStream iis = ImageIO.createImageInputStream(imageFile)) { reader.setInput(iis); // Read the stream metadata // IIOMetadata streamMetadata = reader.getStreamMetadata(); // Set up the writeParam TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US); if (!preserve) { // not preserve original sizes; decompress tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED); } // Read the stream metadata IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam); int imageTotal = reader.getNumImages(true); for (int i = 0; i < imageTotal; i++) { // all if index == -1; otherwise, only index-th if (index == -1 || i == index) { IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam()); File tiffFile = File.createTempFile(OUTPUT_FILE_NAME, TIFF_EXT); try (ImageOutputStream ios = ImageIO.createImageOutputStream(tiffFile)) { writer.setOutput(ios); writer.write(streamMetadata, oimage, tiffWriteParam); tiffFiles.add(tiffFile); } } } return tiffFiles; } finally { if (reader != null) { reader.dispose(); } if (writer != null) { writer.dispose(); } } }