List of usage examples for javax.imageio ImageReader getDefaultReadParam
public ImageReadParam getDefaultReadParam()
From source file:Main.java
public static BufferedImage readFragment(InputStream stream, Rectangle rect) throws IOException { ImageInputStream imageStream = ImageIO.createImageInputStream(stream); ImageReader reader = ImageIO.getImageReaders(imageStream).next(); ImageReadParam param = reader.getDefaultReadParam(); param.setSourceRegion(rect);/*from ww w . jav a 2 s . co m*/ reader.setInput(imageStream, true, true); BufferedImage image = reader.read(0, param); reader.dispose(); imageStream.close(); return image; }
From source file:com.shending.support.CompressPic.java
public static void cut(String srcFile, String dstFile, int widthRange, int heightRange) { int x = 0;//from ww w. j av a 2 s . c o m int y = 0; try { ImageInputStream iis = ImageIO.createImageInputStream(new File(srcFile)); Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis); ImageReader reader = (ImageReader) iterator.next(); reader.setInput(iis, true); ImageReadParam param = reader.getDefaultReadParam(); int oldWidth = reader.getWidth(0); int oldHeight = reader.getHeight(0); int newWidth, newHeight; newWidth = oldHeight * widthRange / heightRange; if (newWidth < oldWidth) { newHeight = oldHeight; x = (oldWidth - newWidth) / 2; } else { newWidth = oldWidth; newHeight = oldWidth * heightRange / widthRange; y = (oldHeight - newHeight) / 2; } Rectangle rectangle = new Rectangle(x, y, newWidth, newHeight); param.setSourceRegion(rectangle); BufferedImage bi = reader.read(0, param); File file = new File(dstFile); ImageIO.write(bi, reader.getFormatName(), file); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.shending.support.CompressPic.java
/** * ?/*from ww w. j a va2s .c o m*/ * * @param srcFile * @param dstFile * @param widthRange * @param heightRange */ public static void cutSquare(String srcFile, String dstFile, int widthRange, int heightRange, int width, int height) { int x = 0; int y = 0; try { ImageInputStream iis = ImageIO.createImageInputStream(new File(srcFile)); Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis); ImageReader reader = (ImageReader) iterator.next(); reader.setInput(iis, true); ImageReadParam param = reader.getDefaultReadParam(); int oldWidth = reader.getWidth(0); int oldHeight = reader.getHeight(0); int newWidth, newHeight; if (width <= oldWidth && height <= oldHeight) { newWidth = oldHeight * widthRange / heightRange; if (newWidth < oldWidth) { newHeight = oldHeight; x = (oldWidth - newWidth) / 2; } else { newWidth = oldWidth; newHeight = oldWidth * heightRange / widthRange; y = (oldHeight - newHeight) / 2; } Rectangle rectangle = new Rectangle(x, y, newWidth, newHeight); param.setSourceRegion(rectangle); BufferedImage bi = reader.read(0, param); BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(bi.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null); File file = new File(dstFile); ImageIO.write(tag, reader.getFormatName(), file); } else { BufferedImage bi = reader.read(0, param); BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = tag.createGraphics(); g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, tag.getWidth(), tag.getHeight()); g2d.drawImage(bi.getScaledInstance(bi.getWidth(), bi.getHeight(), Image.SCALE_SMOOTH), (width - bi.getWidth()) / 2, (height - bi.getHeight()) / 2, null); g2d.dispose(); File file = new File(dstFile); ImageIO.write(tag, reader.getFormatName(), file); } } catch (Exception e) { e.printStackTrace(); } }
From source file:common.utils.ImageUtils.java
/** * closes iis/*w w w. j av a 2 s. co m*/ * @param iis * @return image from given stream or null if no readers found * @throws java.io.IOException */ public static BufferedImageHolder readImage(ImageInputStream iis) throws IOException { ImageReader reader = getImageReader(iis); if (reader == null) { iis.close(); return null; } reader.setInput(iis, true, true); ImageReadParam param = reader.getDefaultReadParam(); String format_name = reader.getFormatName(); BufferedImage bi; try { bi = reader.read(0, param); } finally { reader.dispose(); iis.close(); } return new BufferedImageHolder(bi, format_name); }
From source file:jails.http.converter.BufferedImageHttpMessageConverter.java
public BufferedImage read(Class<? extends BufferedImage> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { ImageInputStream imageInputStream = null; ImageReader imageReader = null; try {// w w w. j a v a 2s . c o m imageInputStream = createImageInputStream(inputMessage.getBody()); MediaType contentType = inputMessage.getHeaders().getContentType(); Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType.toString()); if (imageReaders.hasNext()) { imageReader = imageReaders.next(); ImageReadParam irp = imageReader.getDefaultReadParam(); process(irp); imageReader.setInput(imageInputStream, true); return imageReader.read(0, irp); } else { throw new HttpMessageNotReadableException( "Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]"); } } finally { if (imageReader != null) { imageReader.dispose(); } if (imageInputStream != null) { try { imageInputStream.close(); } catch (IOException ex) { // ignore } } } }
From source file:com.funambol.foundation.util.MediaUtils.java
/** * Creates the thumbnail./* w w w .j a v a 2 s .c om*/ * * @param imageFile the image file * @param thumbFile the empty thumbnail file * @param thumbX the width of the thumbnail * @param thumbY the height of the thumbnail * @param imageName the image file name with extension * @param tolerance the percentage of tolerance before creating a thumbnail * @return true is the thumbnail has been created, false otherwise * @throws IOException if an error occurs */ private static boolean createThumbnail(File imageFile, File thumbFile, int thumbX, int thumbY, String imageName, double tolerance) throws IOException { FileInputStream fileis = null; ImageInputStream imageis = null; Iterator readers = null; try { readers = ImageIO.getImageReadersByFormatName(imageName.substring(imageName.lastIndexOf('.') + 1)); if (readers == null || (!readers.hasNext())) { throw new IOException("File not supported"); } ImageReader reader = (ImageReader) readers.next(); fileis = new FileInputStream(imageFile); imageis = ImageIO.createImageInputStream(fileis); reader.setInput(imageis, true); // Determines thumbnail height, width and quality int thumbWidth = thumbX; int thumbHeight = thumbY; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = reader.getWidth(0); int imageHeight = reader.getHeight(0); // // Don't create the thumbnail if the original file is smaller // than required size increased by % tolerance // if (imageWidth <= (thumbWidth * (1 + tolerance / 100)) && imageHeight <= (thumbHeight * (1 + tolerance / 100))) { return false; } double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } ImageReadParam param = reader.getDefaultReadParam(); param.setSourceSubsampling(3, 3, 0, 0); BufferedImage bi = reader.read(0, param); Image thumb = bi.getScaledInstance(thumbWidth, thumbHeight, Image.SCALE_SMOOTH); BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(thumb, 0, 0, thumbWidth, thumbHeight, null); FileOutputStream fileOutputStream = new FileOutputStream(thumbFile); ImageIO.write(thumbImage, "jpg", fileOutputStream); thumb.flush(); thumbImage.flush(); fileOutputStream.flush(); fileOutputStream.close(); graphics2D.dispose(); } finally { if (fileis != null) { fileis.close(); } if (imageis != null) { imageis.close(); } } return true; }
From source file:net.frontlinesms.plugins.forms.FormsPluginController.java
private void convertByteImageToFile(byte[] imageByte, String path) throws Exception { System.out.println("path ...... convertByteImageToFile ......... " + path); ByteArrayInputStream bis = new ByteArrayInputStream(imageByte); Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg"); ImageReader reader = (ImageReader) readers.next(); Object source = bis;//w w w .ja v a 2s . co m ImageInputStream iis = ImageIO.createImageInputStream(source); reader.setInput(iis, true); ImageReadParam param = reader.getDefaultReadParam(); Image image = reader.read(0, param); //got an image file BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB); //bufferedImage is the RenderedImage to be written Graphics2D g2 = bufferedImage.createGraphics(); g2.drawImage(image, null, null); File imageFile = new File(path); ImageIO.write(bufferedImage, "jpg", imageFile); System.out.println(" end write image "); }
From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java
private IIOImage createImage(InputStream istr, int attempt) throws ImageInterpreterException { ImageInputStream iis = null;//from www . j a v a2 s.c om Iterator<ImageReader> ri = null; ImageReadParam param = null; ImageReader ir = null; BufferedImage bi = null; // Raster raster = null; // int[] bufferTypes = new int[] { DataBuffer.TYPE_BYTE, DataBuffer.TYPE_INT, DataBuffer.TYPE_FLOAT, DataBuffer.TYPE_DOUBLE, // DataBuffer.TYPE_SHORT, DataBuffer.TYPE_USHORT, DataBuffer.TYPE_UNDEFINED }; // Create raster from image reader try { iis = ImageIO.createImageInputStream(istr); ri = ImageIO.getImageReaders(iis); if (!ri.hasNext()) { // List<ImageReader> list = new ArrayList<ImageReader>(); // list.add(new JPEGImageReader(new JPEGImageReaderSpi())); ri = IteratorUtils.getIterator(new JPEGImageReader(new JPEGImageReaderSpi())); } } catch (IOException e) { throw new ImageInterpreterException("Error reading input stream: " + e.toString()); } while (ri.hasNext()) { ir = ri.next(); try { ir.setInput(iis); param = ir.getDefaultReadParam(); bi = ir.read(0, param); // raster = ir.readRaster(0, param); if (bi != null) { break; } } catch (Error e) { LOGGER.error("Failed to render image with ImageReader: " + e.toString()); continue; } catch (Exception e) { LOGGER.error("Failed to render image with ImageReader: " + e.toString()); continue; } } // store metadata IIOMetadata md = null; try { md = getImageMetadata(ir); } catch (ImageInterpreterException e) { LOGGER.error("Failed to extract metadata from image: " + e.getMessage()); InputStream patchedInputStream = null; if (attempt <= 1) { patchedInputStream = attempt == 0 ? new PatchInputStream(istr) : new RemoveHeaderInputStream(istr); if (istr != null) { try { istr.close(); } catch (IOException e1) { LOGGER.error("Failed to close input stream"); } } return createImage(patchedInputStream, attempt + 1); } else { LOGGER.error("Unable to read image metadata."); md = null; } } finally { if (iis != null) { try { iis.close(); } catch (IOException e) { LOGGER.error("Failed to close image stream", e); } } } // // create buffered image from raster // int count = 0; // while (count < bufferTypes.length) { // int bufferType = bufferTypes[count++]; // try { // SampleModel sm = RasterFactory.createPixelInterleavedSampleModel(bufferType, raster.getWidth(), raster.getHeight(), // raster.getNumBands()); // ColorModel cm = PlanarImage.createColorModel(sm); // // cm = bi.getColorModel(); // ColorSpace sourceColorSpace = cm.getColorSpace(); // ColorSpace destColorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB); // ColorConvertOp op = new ColorConvertOp(sourceColorSpace, destColorSpace, null); // // WritableRaster wraster = raster.createInterleavedRaster(bufferTypes[count-1], raster.getWidth(), raster.getHeight(), // raster.getNumBands(), null); // // WritableRaster wraster = op.createCompatibleDestRaster(raster); // WritableRaster wraster = op.filter(raster, null); // // Raster raster2 = bi.getRaster(); // // cm = new ComponentColorModel(cs, false, false, ColorModel.OPAQUE, bufferType); // // sm = bi.getSampleModel(); // // cm = bi.getColorModel(); // // cm = ColorModel.getRGBdefault(); // bi = new BufferedImage(cm, wraster, false, null); // cm.finalize(); // } catch (Error e) { // LOGGER.debug("Failed to render image with BufferType " + bufferType); // continue; // } catch (Exception e) { // LOGGER.debug("Failed to render image with BufferType " + bufferType); // continue; // } // break; // } if (bi == null) { throw new ImageInterpreterException("Failed to extract buffered image from image reader"); } IIOImage image = new IIOImage(bi, null, md); return image; }
From source file:de.cismet.cids.custom.objecteditors.wunda_blau.WebDavPicturePanel.java
/** * DOCUMENT ME!//from w w w. j a v a2s . com * * @param fileName DOCUMENT ME! * * @return DOCUMENT ME! * * @throws Exception DOCUMENT ME! */ private BufferedImage downloadImageFromWebDAV(final String fileName) throws Exception { final InputStream iStream = webdavHelper.getFileFromWebDAV(fileName, webdavDirectory, getConnectionContext()); try { final ImageInputStream iiStream = ImageIO.createImageInputStream(iStream); final Iterator<ImageReader> itReader = ImageIO.getImageReaders(iiStream); if (itReader.hasNext()) { final ImageReader reader = itReader.next(); final ProgressMonitor monitor = new ProgressMonitor(this, "Bild wird bertragen...", "", 0, 100); // monitor.setMillisToPopup(500); reader.addIIOReadProgressListener(new IIOReadProgressListener() { @Override public void sequenceStarted(final ImageReader source, final int minIndex) { } @Override public void sequenceComplete(final ImageReader source) { } @Override public void imageStarted(final ImageReader source, final int imageIndex) { monitor.setProgress(monitor.getMinimum()); } @Override public void imageProgress(final ImageReader source, final float percentageDone) { if (monitor.isCanceled()) { try { iiStream.close(); } catch (final IOException ex) { // NOP } } else { monitor.setProgress(Math.round(percentageDone)); } } @Override public void imageComplete(final ImageReader source) { monitor.setProgress(monitor.getMaximum()); } @Override public void thumbnailStarted(final ImageReader source, final int imageIndex, final int thumbnailIndex) { } @Override public void thumbnailProgress(final ImageReader source, final float percentageDone) { } @Override public void thumbnailComplete(final ImageReader source) { } @Override public void readAborted(final ImageReader source) { monitor.close(); } }); final ImageReadParam param = reader.getDefaultReadParam(); reader.setInput(iiStream, true, true); final BufferedImage result; try { result = reader.read(0, param); } finally { reader.dispose(); iiStream.close(); } return result; } else { return null; } } finally { IOUtils.closeQuietly(iStream); } }
From source file:org.apache.carbondata.sdk.file.ImageTest.java
public void binaryToCarbonWithHWD(String sourceImageFolder, String outputPath, String preDestPath, String sufAnnotation, final String sufImage, int numToWrite) throws Exception { int num = 1;/*from w w w . j a v a2 s . c om*/ Field[] fields = new Field[7]; fields[0] = new Field("height", DataTypes.INT); fields[1] = new Field("width", DataTypes.INT); fields[2] = new Field("depth", DataTypes.INT); fields[3] = new Field("binaryName", DataTypes.STRING); fields[4] = new Field("binary", DataTypes.BINARY); fields[5] = new Field("labelName", DataTypes.STRING); fields[6] = new Field("labelContent", DataTypes.STRING); byte[] originBinary = null; // read and write image data for (int j = 0; j < num; j++) { Object[] files = listFiles(sourceImageFolder, sufImage).toArray(); int index = 0; if (null != files) { CarbonWriter writer = CarbonWriter.builder().outputPath(outputPath).withCsvInput(new Schema(fields)) .withBlockSize(256).writtenBy("SDKS3Example").withPageSizeInMb(1).build(); for (int i = 0; i < files.length; i++) { if (0 == index % numToWrite) { writer.close(); writer = CarbonWriter.builder().outputPath(outputPath).withCsvInput(new Schema(fields)) .withBlockSize(256).writtenBy("SDKS3Example").withPageSizeInMb(1).build(); } index++; // read image and encode to Hex File file = new File((String) files[i]); System.out.println(file.getCanonicalPath()); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); int depth = 0; boolean isGray; boolean hasAlpha; BufferedImage bufferedImage = null; try { bufferedImage = ImageIO.read(file); isGray = bufferedImage.getColorModel().getColorSpace().getType() == ColorSpace.TYPE_GRAY; hasAlpha = bufferedImage.getColorModel().hasAlpha(); if (isGray) { depth = 1; } else if (hasAlpha) { depth = 4; } else { depth = 3; } } catch (Exception e) { e.printStackTrace(); System.out.println(i); ImageInputStream stream = new FileImageInputStream(new File(file.getCanonicalPath())); Iterator<ImageReader> iter = ImageIO.getImageReaders(stream); Exception lastException = null; while (iter.hasNext()) { ImageReader reader = null; try { reader = (ImageReader) iter.next(); ImageReadParam param = reader.getDefaultReadParam(); reader.setInput(stream, true, true); Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0); while (imageTypes.hasNext()) { ImageTypeSpecifier imageTypeSpecifier = imageTypes.next(); System.out .println(imageTypeSpecifier.getColorModel().getColorSpace().getType()); int bufferedImageType = imageTypeSpecifier.getBufferedImageType(); if (bufferedImageType == BufferedImage.TYPE_BYTE_GRAY) { param.setDestinationType(imageTypeSpecifier); break; } } bufferedImage = reader.read(0, param); isGray = bufferedImage.getColorModel().getColorSpace() .getType() == ColorSpace.TYPE_GRAY; hasAlpha = bufferedImage.getColorModel().hasAlpha(); if (isGray) { depth = 1; } else if (hasAlpha) { depth = 4; } else { depth = 3; } if (null != bufferedImage) break; } catch (Exception e2) { lastException = e2; } finally { if (null != reader) reader.dispose(); } } // If you don't have an image at the end of all readers if (null == bufferedImage) { if (null != lastException) { throw lastException; } } } finally { originBinary = new byte[bis.available()]; while ((bis.read(originBinary)) != -1) { } String txtFileName = file.getCanonicalPath().split(sufImage)[0] + sufAnnotation; BufferedInputStream txtBis = new BufferedInputStream(new FileInputStream(txtFileName)); String txtValue = null; byte[] txtBinary = null; txtBinary = new byte[txtBis.available()]; while ((txtBis.read(txtBinary)) != -1) { txtValue = new String(txtBinary, "UTF-8"); } // write data writer.write(new Object[] { bufferedImage.getHeight(), bufferedImage.getWidth(), depth, file.getCanonicalPath(), originBinary, txtFileName, txtValue.replace("\n", "") }); bis.close(); } } writer.close(); } } CarbonReader reader = CarbonReader.builder(outputPath).build(); System.out.println("\nData:"); int i = 0; while (i < 20 && reader.hasNext()) { Object[] row = (Object[]) reader.readNextRow(); byte[] outputBinary = (byte[]) row[1]; System.out.println(row[2] + " " + row[3] + " " + row[4] + " " + row[5] + " image size:" + outputBinary.length + " " + row[0]); // save image, user can compare the save image and original image String destString = preDestPath + i + sufImage; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destString)); bos.write(outputBinary); bos.close(); i++; } System.out.println("\nFinished"); reader.close(); }