List of usage examples for javax.imageio ImageTypeSpecifier ImageTypeSpecifier
public ImageTypeSpecifier(RenderedImage image)
From source file:net.d53dev.dslfy.web.service.GifService.java
public void saveAnimatedGIF(OutputStream out, List<GifFrame> frames, int loopCount) throws Exception { ImageWriter iw = ImageIO.getImageWritersByFormatName("gif").next(); ImageOutputStream ios = ImageIO.createImageOutputStream(out); iw.setOutput(ios);//from w w w. j a v a 2 s . c om iw.prepareWriteSequence(null); int p = 0; for (GifFrame frame : frames) { ImageWriteParam iwp = iw.getDefaultWriteParam(); IIOMetadata metadata = iw.getDefaultImageMetadata(new ImageTypeSpecifier(frame.img), iwp); this.configureGIFFrame(metadata, String.valueOf(frame.delay / 10L), p++, frame.disposalMethod, loopCount); IIOImage ii = new IIOImage(frame.img, null, metadata); iw.writeToSequence(ii, null); } iw.endWriteSequence(); ios.close(); }
From source file:com.ackpdfbox.app.imageio.ImageIOUtil.java
/** * Writes a buffered image to a file using the given image format. * Compression is fixed for PNG, GIF, BMP and WBMP, dependent of the quality * parameter for JPG, and dependent of bit count for TIFF (a bitonal image * will be compressed with CCITT G4, a color image with LZW). Creating a * TIFF image is only supported if the jai_imageio library is in the class * path.//from ww w . j a v a2 s .c om * * @param image the image to be written * @param formatName the target format (ex. "png") * @param output the output stream to be used for writing * @param dpi the resolution in dpi (dots per inch) to be used in metadata * @param quality quality to be used when compressing the image (0 < * quality < 1.0f) * @return true if the image file was produced, false if there was an error. * @throws IOException if an I/O error occurs */ public static boolean writeImage(BufferedImage image, String formatName, OutputStream output, int dpi, float quality) throws IOException { ImageOutputStream imageOutput = null; ImageWriter writer = null; try { // find suitable image writer Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(formatName); ImageWriteParam param = null; IIOMetadata metadata = null; // Loop until we get the best driver, i.e. one that supports // setting dpi in the standard metadata format; however we'd also // accept a driver that can't, if a better one can't be found while (writers.hasNext()) { if (writer != null) { writer.dispose(); } writer = writers.next(); param = writer.getDefaultWriteParam(); metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param); if (metadata != null && !metadata.isReadOnly() && metadata.isStandardMetadataFormatSupported()) { break; } } if (writer == null) { LOG.error("No ImageWriter found for '" + formatName + "' format"); StringBuilder sb = new StringBuilder(); String[] writerFormatNames = ImageIO.getWriterFormatNames(); for (String fmt : writerFormatNames) { sb.append(fmt); sb.append(' '); } LOG.error("Supported formats: " + sb); return false; } // compression if (param != null && param.canWriteCompressed()) { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); if (formatName.toLowerCase().startsWith("tif")) { // TIFF compression TIFFUtil.setCompressionType(param, image); } else { param.setCompressionType(param.getCompressionTypes()[0]); param.setCompressionQuality(quality); } } if (formatName.toLowerCase().startsWith("tif")) { // TIFF metadata TIFFUtil.updateMetadata(metadata, image, dpi); } else if ("jpeg".equals(formatName.toLowerCase()) || "jpg".equals(formatName.toLowerCase())) { // This segment must be run before other meta operations, // or else "IIOInvalidTreeException: Invalid node: app0JFIF" // The other (general) "meta" methods may not be used, because // this will break the reading of the meta data in tests JPEGUtil.updateMetadata(metadata, dpi); } else { // write metadata is possible if (metadata != null && !metadata.isReadOnly() && metadata.isStandardMetadataFormatSupported()) { setDPI(metadata, dpi, formatName); } } // write imageOutput = ImageIO.createImageOutputStream(output); writer.setOutput(imageOutput); writer.write(null, new IIOImage(image, null, metadata), param); } finally { if (writer != null) { writer.dispose(); } if (imageOutput != null) { imageOutput.close(); } } return true; }
From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java
/************************************************************************************ * Write the renderedimage to an {@link OutputStream} * /*from w w w.j av a 2 s .com*/ * @param outStream the {@link OutputStream} to write to ************************************************************************************/ @Override public void writeToStream(FileOutputStream fos, OutputStream outStream) { if (this.renderedimage == null) { // no image available return; } try { // create a buffered Image, which has no Alpha channel // as JPEG does not support Alpha Channels and the // ImageIO doesn't care - but will create a corrupt JPEG BufferedImage noAlphaBi = ImageManipulator.fromRenderedToBufferedNoAlpha(renderedimage); ImageOutputStream imageOutStream = ImageIO.createImageOutputStream(outStream); // Iterator<ImageWriter> writerIter = ImageIO // .getImageWritersByFormatName("jpg"); // ImageWriter writer = writerIter.next(); // get writer from ImageIO ImageWriter writer = new JPEGImageWriter(new JPEGImageWriterSpi()); // create metadata by creating an XML tree ImageWriteParam writerParam = writer.getDefaultWriteParam(); ImageTypeSpecifier its = new ImageTypeSpecifier(noAlphaBi); // ImageTypeSpecifier its = new // ImageTypeSpecifier(image.getColorModel(), // image.getSampleModel()); // IIOMetadata iomd = writer.getDefaultImageMetadata(new // ImageTypeSpecifier(image), writerParam); // Element tree = // (Element)iomd.getAsTree("javax_imageio_jpeg_image_1.0"); // Element tree = (Element)iomd.getAsTree("javax_imageio_1.0"); // IIOMetadata iomd = writer.getDefaultImageMetadata(its, writerParam); // create the XML tree and modify the appropriate DOM elements // to set the metadata setMetadata(iomd); // set compression writerParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); float comprvalue = ((float) writerCompressionValue) / 100; writerParam.setCompressionQuality(comprvalue); // set output writer.setOutput(imageOutStream); writer.prepareWriteSequence(null); // create new image parameters to set the compression // Locale locale = new Locale("en"); // JPEGImageWriteParam jpegWriteParam = new // JPEGImageWriteParam(locale); // IIOImage iioImage = new IIOImage(renderedimage, null, iomd); IIOImage iioImage = new IIOImage(noAlphaBi, null, iomd); writer.write(null, iioImage, writerParam); writer.endWriteSequence(); imageOutStream.flush(); if (fos != null) { ImageOutputStream imageToFile = ImageIO.createImageOutputStream(fos); writer.setOutput(imageToFile); writer.prepareWriteSequence(null); writer.write(null, iioImage, writerParam); writer.endWriteSequence(); imageToFile.flush(); imageToFile.close(); fos.flush(); fos.close(); } // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // byte [] data = wi.getImageAsByteArray(); writer.dispose(); imageOutStream.close(); } catch (IOException e) { LOGGER.error("IOException occured", e); } }
From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java
@Override public byte[] writeToStreamAndByteArray(OutputStream outStream) { byte[] data = null; if (this.renderedimage == null) { // no image available return data; }//w w w . j a va 2 s.co m try { // create a buffered Image, which has no Alpha channel // as JPEG does not support Alpha Channels and the // ImageIO doesn't care - but will create a corrupt JPEG BufferedImage noAlphaBi = ImageManipulator.fromRenderedToBufferedNoAlpha(renderedimage); ImageOutputStream imageOutStream = ImageIO.createImageOutputStream(outStream); // Iterator<ImageWriter> writerIter = ImageIO // .getImageWritersByFormatName("jpg"); // ImageWriter writer = writerIter.next(); // get writer from ImageIO ImageWriter writer = new JPEGImageWriter(new JPEGImageWriterSpi()); // create metadata by creating an XML tree ImageWriteParam writerParam = writer.getDefaultWriteParam(); ImageTypeSpecifier its = new ImageTypeSpecifier(noAlphaBi); // ImageTypeSpecifier its = new // ImageTypeSpecifier(image.getColorModel(), // image.getSampleModel()); // IIOMetadata iomd = writer.getDefaultImageMetadata(new // ImageTypeSpecifier(image), writerParam); // Element tree = // (Element)iomd.getAsTree("javax_imageio_jpeg_image_1.0"); // Element tree = (Element)iomd.getAsTree("javax_imageio_1.0"); // IIOMetadata iomd = writer.getDefaultImageMetadata(its, writerParam); // create the XML tree and modify the appropriate DOM elements // to set the metadata setMetadata(iomd); // set compression writerParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); float comprvalue = ((float) writerCompressionValue) / 100; writerParam.setCompressionQuality(comprvalue); // set output writer.setOutput(imageOutStream); writer.prepareWriteSequence(null); // create new image parameters to set the compression // Locale locale = new Locale("en"); // JPEGImageWriteParam jpegWriteParam = new // JPEGImageWriteParam(locale); // IIOImage iioImage = new IIOImage(renderedimage, null, iomd); IIOImage iioImage = new IIOImage(noAlphaBi, null, iomd); writer.write(null, iioImage, writerParam); writer.endWriteSequence(); imageOutStream.flush(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageOutputStream imageToFile = ImageIO.createImageOutputStream(baos); writer.setOutput(imageToFile); writer.prepareWriteSequence(null); writer.write(null, iioImage, writerParam); writer.endWriteSequence(); imageToFile.flush(); imageToFile.close(); baos.flush(); data = baos.toByteArray(); baos.close(); writer.dispose(); imageOutStream.close(); } catch (IOException e) { LOGGER.error("IOException occured", e); } return data; }
From source file:nl.softwaredesign.exporter.ODTExportFormat.java
/** * TODO Move to utility class?//ww w. j a v a 2s.c o m * Extract the content data (bytes) from the given image. * @param icon image to get bytes for * @param format desired format for image * @param background Color to use as background if transparency in image * @param width Desired width of the image in the byte array * @param height Desired width of the image in the byte array * @return the bytes of the image * @throws IOException */ private byte[] imageToBytes(ImageIcon icon, String format, Color background, int width, int height) throws IOException { Iterator writers = ImageIO.getImageWritersByFormatName(format); ImageWriter writer = (ImageWriter) writers.next(); ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageOutputStream ios = ImageIO.createImageOutputStream(output); writer.setOutput(ios); BufferedImage img; if ("png".equalsIgnoreCase(format) || "gif".equalsIgnoreCase(format)) { img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); } else { img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); } WaitingObserver observer = new WaitingObserver(); if (!img.getGraphics().drawImage(icon.getImage(), 0, 0, width, height, background, observer)) { try { observer.waitForDone(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return new byte[0]; } } IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(img), writer.getDefaultWriteParam()); if (format.equalsIgnoreCase("jpg")) { Element tree = (Element) metadata.getAsTree("javax_imageio_jpeg_image_1.0"); Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0); jfif.setAttribute("Xdensity", Integer.toString(72)); jfif.setAttribute("Ydensity", Integer.toString(72)); jfif.setAttribute("resUnits", "1"); metadata.setFromTree("javax_imageio_jpeg_image_1.0", tree); } else { double dotsPerMilli = 7.2 / 2.54; IIOMetadataNode horiz = new IIOMetadataNode("HorizontalPixelSize"); horiz.setAttribute("value", Double.toString(dotsPerMilli)); IIOMetadataNode vert = new IIOMetadataNode("VerticalPixelSize"); vert.setAttribute("value", Double.toString(dotsPerMilli)); IIOMetadataNode dim = new IIOMetadataNode("Dimension"); dim.appendChild(horiz); dim.appendChild(vert); IIOMetadataNode root = new IIOMetadataNode("javax_imageio_1.0"); root.appendChild(dim); metadata.mergeTree("javax_imageio_1.0", root); } writer.write(null, new IIOImage(img, null, metadata), null); return output.toByteArray(); }
From source file:org.geotools.utils.imageoverviews.OverviewsEmbedder.java
public void run() { // did we create a local private tile cache or not? boolean localTileCache = false; ///*from w ww .j a v a 2 s . c o m*/ // creating the image to use for the successive // subsampling // TileCache baseTC = JAI.getDefaultInstance().getTileCache(); if (baseTC == null) { localTileCache = true; final long tilecacheSize = super.getTileCacheSize(); baseTC = JAI.createTileCache(); baseTC.setMemoryCapacity(tilecacheSize); baseTC.setMemoryThreshold(0.75f); } // // CHECK INPUT DIRECTORIES/FILES // if (sourcePath == null) { fireEvent("Provided sourcePath is null", overallProgress); return; } // getting an image input stream to the file final File file = new File(sourcePath); final File[] files; int numFiles = 1; StringBuilder message; if (!file.canRead() || !file.exists()) { fireEvent("Provided file " + file.getAbsolutePath() + " cannot be read or does not exist", 100); return; } if (file.isDirectory()) { if (wildcardString == null) { fireEvent("Provided wildcardString is null", 100); return; } final FileFilter fileFilter = new WildcardFileFilter(wildcardString); files = file.listFiles(fileFilter); numFiles = files.length; if (numFiles <= 0) { message = new StringBuilder("No files to process!"); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } fireEvent(message.toString(), 100); } } else files = new File[] { file }; if (files == null || files.length == 0) { fireEvent("Unable to find input files for the provided wildcard " + wildcardString + " and input path " + sourcePath, 100); return; } // setting step overallProgressStep = 100 * 1.0 / numFiles; // // ADDING OVERVIEWS TO ALL FOUND FILES // for (fileBeingProcessed = 0; fileBeingProcessed < numFiles; fileBeingProcessed++) { message = new StringBuilder("Managing file ").append(fileBeingProcessed).append(" of ") .append(files[fileBeingProcessed]).append(" files"); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } overallProgress = overallProgressStep * fileBeingProcessed; fireEvent(message.toString(), overallProgress); if (getStopThread()) { message = new StringBuilder("Stopping requested at file ").append(fileBeingProcessed) .append(" of ").append(numFiles).append(" files"); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } fireEvent(message.toString(), overallProgress); return; } ImageInputStream stream = null; ImageWriter writer = null; ImageOutputStream streamOut = null; RenderedOp currentImage = null; RenderedOp newImage = null; try { File localFile = files[fileBeingProcessed]; // // get a stream // stream = ImageIO.createImageInputStream(localFile); if (stream == null) { message = new StringBuilder("Unable to create an input stream for file") .append(files[fileBeingProcessed]); if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.severe(message.toString()); } fireEvent(message.toString(), overallProgress); break; } stream.mark(); // // get a reader // final Iterator<ImageReader> it = ImageIO.getImageReaders(stream); if (!it.hasNext()) { message = new StringBuilder("Unable to find a reader for file") .append(files[fileBeingProcessed]); if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.severe(message.toString()); } fireEvent(message.toString(), overallProgress); break; } final ImageReader reader = (ImageReader) it.next(); stream.reset(); stream.mark(); // is it a geotiff reader or not? if (!reader.getFormatName().toLowerCase().startsWith("tif")) { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("Discarding input file " + files[fileBeingProcessed] + " since it is not a proper tif file."); } continue; } // // set input // reader.setInput(stream); ImageLayout layout = null; // tiling the image if needed int actualTileW = reader.getTileWidth(0); int actualTileH = reader.getTileHeight(0); if (!reader.isImageTiled(0) || (reader.isImageTiled(0) && (actualTileH != tileH && tileH != -1) || (actualTileW != tileW && tileW != -1))) { message = new StringBuilder("Retiling image ").append(fileBeingProcessed); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } fireEvent(message.toString(), overallProgress); layout = Utils.createTiledLayout(tileW, tileH, 0, 0); } stream.reset(); reader.reset(); reader.dispose(); // // output image stream // if (externalOverviews) { // create a sibling file localFile = new File(localFile.getParent(), FilenameUtils.getBaseName(localFile.getAbsolutePath()) + ".tif.ovr"); } streamOut = ImageIOExt.createImageOutputStream(null, localFile); if (streamOut == null) { message = new StringBuilder("Unable to acquire an ImageOutputStream for the file ") .append(files[fileBeingProcessed].toString()); if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.severe(message.toString()); } fireEvent(message.toString(), 100); break; } // // Preparing to write the set of images. First of all I write // the first image ` // // getting a writer for this reader writer = TIFF_IMAGE_WRITER_SPI.createWriterInstance(); writer.setOutput(streamOut); writer.addIIOWriteProgressListener(writeProgressListener); writer.addIIOWriteWarningListener(writeProgressListener); ImageWriteParam param = writer.getDefaultWriteParam(); // // setting tiling on the first image using writing parameters // if (tileH != -1 & tileW != -1) { param.setTilingMode(ImageWriteParam.MODE_EXPLICIT); param.setTiling(tileW, tileH, 0, 0); } else { param.setTilingMode(ImageWriteParam.MODE_EXPLICIT); param.setTiling(actualTileW, actualTileH, 0, 0); } if (this.compressionScheme != null && !Double.isNaN(compressionRatio)) { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionType(compressionScheme); param.setCompressionQuality((float) this.compressionRatio); } final RenderingHints newHints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout); newHints.add(new RenderingHints(JAI.KEY_TILE_CACHE, baseTC)); // read base image ParameterBlock pbjRead = new ParameterBlock(); pbjRead.add(stream); pbjRead.add(Integer.valueOf(0)); pbjRead.add(Boolean.FALSE); pbjRead.add(Boolean.FALSE); pbjRead.add(Boolean.FALSE); pbjRead.add(null); pbjRead.add(null); pbjRead.add(null); pbjRead.add(null); currentImage = JAI.create("ImageRead", pbjRead, newHints); message = new StringBuilder("Read original image ").append(fileBeingProcessed); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } fireEvent(message.toString(), overallProgress); int i = 0; // // OVERVIEWS CYLE // for (overviewInProcess = 0; overviewInProcess < numSteps; overviewInProcess++) { message = new StringBuilder("Subsampling step ").append(overviewInProcess + 1) .append(" of image ").append(fileBeingProcessed); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } fireEvent(message.toString(), overallProgress); // paranoiac check if (currentImage.getWidth() / downsampleStep <= 0 || currentImage.getHeight() / downsampleStep <= 0) break; // SCALE // subsampling the input image using the chosen algorithm final SubsampleAlgorithm algorithm = SubsampleAlgorithm.valueOf(scaleAlgorithm); switch (algorithm) { case Average: newImage = Utils.scaleAverage(currentImage, baseTC, downsampleStep, borderExtender); break; case Filtered: newImage = Utils.filteredSubsample(currentImage, baseTC, downsampleStep, lowPassFilter); break; case Bilinear: newImage = Utils.subsample(currentImage, baseTC, new InterpolationBilinear(), downsampleStep, borderExtender); break; case Bicubic: newImage = Utils.subsample(currentImage, baseTC, new InterpolationBicubic(2), downsampleStep, borderExtender); break; case Nearest: newImage = Utils.subsample(currentImage, baseTC, new InterpolationNearest(), downsampleStep, borderExtender); break; default: throw new IllegalArgumentException("Invalid scaling algorithm " + scaleAlgorithm);//cannot get here } //set relevant metadata IIOMetadata imageMetadata = null; if (writer instanceof TIFFImageWriter) { imageMetadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(newImage), param); if (imageMetadata != null) ((TIFFImageMetadata) imageMetadata).addShortOrLongField( BaselineTIFFTagSet.TAG_NEW_SUBFILE_TYPE, BaselineTIFFTagSet.NEW_SUBFILE_TYPE_REDUCED_RESOLUTION); } // write out if (!externalOverviews || i > 0) writer.writeInsert(-1, new IIOImage(newImage, null, imageMetadata), param); else writer.write(null, new IIOImage(newImage, null, imageMetadata), param); message = new StringBuilder("Step ").append(overviewInProcess + 1).append(" of image ") .append(fileBeingProcessed).append(" done!"); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } fireEvent(message.toString(), overallProgress); // switching images currentImage.dispose(); //dispose old image currentImage = newImage; i++; } overallProgress = 100; // close message message = new StringBuilder("Done with image ").append(fileBeingProcessed); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } fireEvent(message.toString(), overallProgress); } catch (Throwable e) { fireException(e); } finally { // clean up // clean caches if they are local if (localTileCache && baseTC != null) try { baseTC.flush(); } catch (Exception e) { } // // free everything try { if (streamOut != null) streamOut.close(); } catch (Throwable e) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e); } try { if (writer != null) writer.dispose(); } catch (Throwable e) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e); } try { if (currentImage != null) currentImage.dispose(); } catch (Throwable e) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e); } try { if (newImage != null) newImage.dispose(); } catch (Throwable e) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e); } try { if (stream != null) stream.close(); } catch (Throwable e) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e); } } } if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Done!!!"); }
From source file:org.modelibra.util.ImageHandler.java
/** * Saves an image to a jpeg file./*from w w w .j ava 2s . c om*/ * * @param bi * buffered image * @param file * jpeg file * @param quality * image quality */ public static void saveImageToJPEGFile14(BufferedImage bi, File file, float quality) throws IOException { JPEGImageWriteParam param = new JPEGImageWriteParam(null); ImageTypeSpecifier type = new ImageTypeSpecifier(bi); param.setDestinationType(type); ImageOutputStream imgos = ImageIO.createImageOutputStream(file); Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpeg"); ImageWriter writer = writers.next(); writer.setOutput(imgos); writer.write(bi); imgos.close(); }
From source file:org.sejda.sambox.pdmodel.graphics.image.JPEGFactory.java
private static void encodeImageToJPEGStream(BufferedImage image, float quality, int dpi, OutputStream out) throws IOException { // encode to JPEG ImageOutputStream ios = null; ImageWriter imageWriter = null; try {//from w w w .j av a 2 s .c o m // find JAI writer imageWriter = ImageIO.getImageWritersBySuffix("jpeg").next(); ios = ImageIO.createImageOutputStream(out); imageWriter.setOutput(ios); // add compression JPEGImageWriteParam jpegParam = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam(); jpegParam.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT); jpegParam.setCompressionQuality(quality); // add metadata ImageTypeSpecifier imageTypeSpecifier = new ImageTypeSpecifier(image); IIOMetadata data = imageWriter.getDefaultImageMetadata(imageTypeSpecifier, jpegParam); Element tree = (Element) data.getAsTree("javax_imageio_jpeg_image_1.0"); Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0); jfif.setAttribute("Xdensity", Integer.toString(dpi)); jfif.setAttribute("Ydensity", Integer.toString(dpi)); jfif.setAttribute("resUnits", "1"); // 1 = dots/inch // write imageWriter.write(data, new IIOImage(image, null, null), jpegParam); } finally { // clean up IOUtils.closeQuietly(out); if (ios != null) { ios.close(); } if (imageWriter != null) { imageWriter.dispose(); } } }