List of usage examples for javax.imageio ImageWriter write
public abstract void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException;
From source file:org.apache.flex.compiler.internal.embedding.transcoders.JPEGTranscoder.java
private byte[] bufferedImageToJPEG(ImageInfo imageInfo, int[] pixels) throws Exception { BufferedImage bufferedImage = new BufferedImage(imageInfo.width, imageInfo.height, BufferedImage.TYPE_INT_ARGB); bufferedImage.setRGB(0, 0, imageInfo.width, imageInfo.height, pixels, 0, imageInfo.width); ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next(); ImageWriteParam writeParam = writer.getDefaultWriteParam(); ColorModel colorModel = new DirectColorModel(24, 0x00ff0000, 0x0000ff00, 0x000000ff); ImageTypeSpecifier imageTypeSpecifier = new ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(1, 1)); writeParam.setDestinationType(imageTypeSpecifier); writeParam.setSourceBands(new int[] { 0, 1, 2 }); writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); float q = 1.0f; if (quality != null) q = quality.floatValue();//from w w w . ja v a 2 s .c o m writeParam.setCompressionQuality(q); DAByteArrayOutputStream buffer = new DAByteArrayOutputStream(); writer.setOutput(new MemoryCacheImageOutputStream(buffer)); IIOImage ioImage = new IIOImage(bufferedImage, null, null); writer.write(null, ioImage, writeParam); writer.dispose(); return buffer.getDirectByteArray(); }
From source file:com.lingxiang2014.util.ImageUtils.java
public static void addWatermark(File srcFile, File destFile, File watermarkFile, int alpha) { Assert.notNull(srcFile);/* w ww . j ava 2 s .com*/ Assert.notNull(destFile); Assert.state(alpha >= 0); Assert.state(alpha <= 100); if (watermarkFile == null || !watermarkFile.exists()) { try { FileUtils.copyFile(srcFile, destFile); } catch (IOException e) { e.printStackTrace(); } return; } if (type == Type.jdk) { Graphics2D graphics2D = null; ImageOutputStream imageOutputStream = null; ImageWriter imageWriter = null; try { BufferedImage srcBufferedImage = ImageIO.read(srcFile); int srcWidth = srcBufferedImage.getWidth(); int srcHeight = srcBufferedImage.getHeight(); BufferedImage destBufferedImage = new BufferedImage(srcWidth, srcHeight, BufferedImage.TYPE_INT_RGB); graphics2D = destBufferedImage.createGraphics(); graphics2D.setBackground(BACKGROUND_COLOR); graphics2D.clearRect(0, 0, srcWidth, srcHeight); graphics2D.drawImage(srcBufferedImage, 0, 0, null); graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100F)); BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile); int watermarkImageWidth = watermarkBufferedImage.getWidth(); int watermarkImageHeight = watermarkBufferedImage.getHeight(); int x = srcWidth - watermarkImageWidth; int y = srcHeight - watermarkImageHeight; graphics2D.drawImage(watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null); imageOutputStream = ImageIO.createImageOutputStream(destFile); imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName())) .next(); imageWriter.setOutput(imageOutputStream); ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam(); imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); imageWriteParam.setCompressionQuality(DEST_QUALITY / 100F); imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam); imageOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (graphics2D != null) { graphics2D.dispose(); } if (imageWriter != null) { imageWriter.dispose(); } if (imageOutputStream != null) { try { imageOutputStream.close(); } catch (IOException e) { } } } } else { IMOperation operation = new IMOperation(); operation.dissolve(alpha); operation.quality((double) DEST_QUALITY); operation.addImage(watermarkFile.getPath()); operation.addImage(srcFile.getPath()); operation.addImage(destFile.getPath()); if (type == Type.graphicsMagick) { CompositeCmd compositeCmd = new CompositeCmd(true); if (graphicsMagickPath != null) { compositeCmd.setSearchPath(graphicsMagickPath); } try { compositeCmd.run(operation); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IM4JavaException e) { e.printStackTrace(); } } else { CompositeCmd compositeCmd = new CompositeCmd(false); if (imageMagickPath != null) { compositeCmd.setSearchPath(imageMagickPath); } try { compositeCmd.run(operation); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IM4JavaException e) { e.printStackTrace(); } } } }
From source file:net.groupbuy.util.ImageUtils.java
/** * //w ww. jav a2 s . c o m * * @param srcFile * ? * @param destFile * * @param destWidth * * @param destHeight * */ public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) { Assert.notNull(srcFile); Assert.notNull(destFile); Assert.state(destWidth > 0); Assert.state(destHeight > 0); if (type == Type.jdk) { Graphics2D graphics2D = null; ImageOutputStream imageOutputStream = null; ImageWriter imageWriter = null; try { BufferedImage srcBufferedImage = ImageIO.read(srcFile); int srcWidth = srcBufferedImage.getWidth(); int srcHeight = srcBufferedImage.getHeight(); int width = destWidth; int height = destHeight; if (srcHeight >= srcWidth) { width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth)); } else { height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight)); } BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB); graphics2D = destBufferedImage.createGraphics(); graphics2D.setBackground(BACKGROUND_COLOR); graphics2D.clearRect(0, 0, destWidth, destHeight); graphics2D.drawImage(srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), (destWidth / 2) - (width / 2), (destHeight / 2) - (height / 2), null); imageOutputStream = ImageIO.createImageOutputStream(destFile); imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName())) .next(); imageWriter.setOutput(imageOutputStream); ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam(); imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0)); imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam); imageOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (graphics2D != null) { graphics2D.dispose(); } if (imageWriter != null) { imageWriter.dispose(); } if (imageOutputStream != null) { try { imageOutputStream.close(); } catch (IOException e) { } } } } else { IMOperation operation = new IMOperation(); operation.thumbnail(destWidth, destHeight); operation.gravity("center"); operation.background(toHexEncoding(BACKGROUND_COLOR)); operation.extent(destWidth, destHeight); operation.quality((double) DEST_QUALITY); operation.addImage(srcFile.getPath()); operation.addImage(destFile.getPath()); if (type == Type.graphicsMagick) { ConvertCmd convertCmd = new ConvertCmd(true); if (graphicsMagickPath != null) { convertCmd.setSearchPath(graphicsMagickPath); } try { convertCmd.run(operation); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IM4JavaException e) { e.printStackTrace(); } } else { ConvertCmd convertCmd = new ConvertCmd(false); if (imageMagickPath != null) { convertCmd.setSearchPath(imageMagickPath); } try { convertCmd.run(operation); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IM4JavaException e) { e.printStackTrace(); } } } }
From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java
/** * Stores BufferedImage as JPEG2000 encoded file. * * @param bi//from ww w . j a v a2 s.c om * @param filename * @param dEncRate * @param lossless * @throws IOException */ public static void storeBIAsJP2File(BufferedImage bi, String filename, double dEncRate, boolean lossless) throws IOException { if (hasJPEG2000FileTag(filename)) { IIOImage iioImage = new IIOImage(bi, null, null); ImageWriter jp2iw = ImageIO.getImageWritersBySuffix("jp2").next(); J2KImageWriteParam writeParam = (J2KImageWriteParam) jp2iw.getDefaultWriteParam(); // Indicates using the lossless scheme or not. It is equivalent to use reversible quantization and 5x3 integer wavelet filters. The default is true. writeParam.setLossless(lossless); if (lossless) writeParam.setFilter(J2KImageWriteParam.FILTER_53); // Specifies which wavelet filters to use for the specified tile-components. JPEG 2000 part I only supports w5x3 and w9x7 filters. else writeParam.setFilter(J2KImageWriteParam.FILTER_97); if (!lossless) { // The bitrate in bits-per-pixel for encoding. Should be set when lossy compression scheme is used. With the default value Double.MAX_VALUE, a lossless compression will be done. writeParam.setEncodingRate(dEncRate); // changes in compression rate are done in the following way // however JPEG2000 implementation seems not to support this <-- no differences visible // writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // writeParam.setCompressionType(writeParam.getCompressionTypes()[0]); // writeParam.setCompressionQuality(1.0f); } ImageOutputStream ios = null; try { ios = new FileImageOutputStream(new File(filename)); jp2iw.setOutput(ios); jp2iw.write(null, iioImage, writeParam); jp2iw.dispose(); ios.flush(); } finally { if (ios != null) ios.close(); } } else System.err.println("please name your file as valid JPEG2000 file: ends with .jp2"); }
From source file:com.el.ecom.utils.ImageUtils.java
/** * /* w ww . j a va2 s. co m*/ * * @param srcFile ? * @param destFile * @param destWidth * @param destHeight */ public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) { Assert.notNull(srcFile); Assert.state(srcFile.exists()); Assert.state(srcFile.isFile()); Assert.notNull(destFile); Assert.state(destWidth > 0); Assert.state(destHeight > 0); if (type == Type.jdk) { Graphics2D graphics2D = null; ImageOutputStream imageOutputStream = null; ImageWriter imageWriter = null; try { BufferedImage srcBufferedImage = ImageIO.read(srcFile); int srcWidth = srcBufferedImage.getWidth(); int srcHeight = srcBufferedImage.getHeight(); int width = destWidth; int height = destHeight; if (srcHeight >= srcWidth) { width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth)); } else { height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight)); } BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB); graphics2D = destBufferedImage.createGraphics(); graphics2D.setBackground(BACKGROUND_COLOR); graphics2D.clearRect(0, 0, destWidth, destHeight); graphics2D.drawImage(srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), (destWidth / 2) - (width / 2), (destHeight / 2) - (height / 2), null); imageOutputStream = ImageIO.createImageOutputStream(destFile); imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName())) .next(); imageWriter.setOutput(imageOutputStream); ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam(); imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0)); imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam); imageOutputStream.flush(); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { if (graphics2D != null) { graphics2D.dispose(); } if (imageWriter != null) { imageWriter.dispose(); } try { if (imageOutputStream != null) { imageOutputStream.close(); } } catch (IOException e) { } } } else { IMOperation operation = new IMOperation(); operation.thumbnail(destWidth, destHeight); operation.gravity("center"); operation.background(toHexEncoding(BACKGROUND_COLOR)); operation.extent(destWidth, destHeight); operation.quality((double) DEST_QUALITY); try { operation.addImage(srcFile.getCanonicalPath()); operation.addImage(destFile.getCanonicalPath()); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } if (type == Type.graphicsMagick) { ConvertCmd convertCmd = new ConvertCmd(true); if (graphicsMagickPath != null) { convertCmd.setSearchPath(graphicsMagickPath); } try { convertCmd.run(operation); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage(), e); } catch (IM4JavaException e) { throw new RuntimeException(e.getMessage(), e); } } else { ConvertCmd convertCmd = new ConvertCmd(false); if (imageMagickPath != null) { convertCmd.setSearchPath(imageMagickPath); } try { convertCmd.run(operation); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage(), e); } catch (IM4JavaException e) { throw new RuntimeException(e.getMessage(), e); } } } }
From source file:org.tinymediamanager.core.ImageCache.java
/** * Cache image./*from w w w . j a v a2s . c o m*/ * * @param mf * the media file * @return the file the cached file * @throws Exception */ public static Path cacheImage(Path originalFile) throws Exception { MediaFile mf = new MediaFile(originalFile); Path cachedFile = ImageCache.getCacheDir() .resolve(getMD5(originalFile.toString()) + "." + Utils.getExtension(originalFile)); if (!Files.exists(cachedFile)) { // check if the original file exists && size > 0 if (!Files.exists(originalFile)) { throw new FileNotFoundException("unable to cache file: " + originalFile + "; file does not exist"); } if (Files.size(originalFile) == 0) { throw new EmptyFileException(originalFile); } // recreate cache dir if needed // rescale & cache BufferedImage originalImage = null; try { originalImage = createImage(originalFile); } catch (Exception e) { throw new Exception("cannot create image - file seems not to be valid? " + originalFile); } // calculate width based on MF type int desiredWidth = originalImage.getWidth(); // initialize with fallback switch (mf.getType()) { case FANART: if (originalImage.getWidth() > 1000) { desiredWidth = 1000; } break; case POSTER: if (originalImage.getHeight() > 500) { desiredWidth = 350; } break; case EXTRAFANART: case THUMB: case BANNER: case GRAPHIC: desiredWidth = 300; break; default: break; } // special handling for movieset-fanart or movieset-poster if (mf.getFilename().startsWith("movieset-fanart") || mf.getFilename().startsWith("movieset-poster")) { if (originalImage.getWidth() > 1000) { desiredWidth = 1000; } } Point size = calculateSize(desiredWidth, (int) (originalImage.getHeight() / 1.5), originalImage.getWidth(), originalImage.getHeight(), true); BufferedImage scaledImage = null; if (Globals.settings.getImageCacheType() == CacheType.FAST) { // scale fast scaledImage = Scalr.resize(originalImage, Scalr.Method.BALANCED, Scalr.Mode.FIT_EXACT, size.x, size.y); } else { // scale with good quality scaledImage = Scalr.resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.FIT_EXACT, size.x, size.y); } originalImage = null; ImageWriter imgWrtr = null; ImageWriteParam imgWrtrPrm = null; // here we have two different ways to create our thumb // a) a scaled down jpg/png (without transparency) which we have to modify since OpenJDK cannot call native jpg encoders // b) a scaled down png (with transparency) which we can store without any more modifying as png if (hasTransparentPixels(scaledImage)) { // transparent image -> png imgWrtr = ImageIO.getImageWritersByFormatName("png").next(); imgWrtrPrm = imgWrtr.getDefaultWriteParam(); } else { // non transparent image -> jpg // convert to rgb BufferedImage rgb = new BufferedImage(scaledImage.getWidth(), scaledImage.getHeight(), BufferedImage.TYPE_INT_RGB); ColorConvertOp xformOp = new ColorConvertOp(null); xformOp.filter(scaledImage, rgb); imgWrtr = ImageIO.getImageWritersByFormatName("jpg").next(); imgWrtrPrm = imgWrtr.getDefaultWriteParam(); imgWrtrPrm.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT); imgWrtrPrm.setCompressionQuality(0.80f); scaledImage = rgb; } FileImageOutputStream output = new FileImageOutputStream(cachedFile.toFile()); imgWrtr.setOutput(output); IIOImage image = new IIOImage(scaledImage, null, null); imgWrtr.write(null, image, imgWrtrPrm); imgWrtr.dispose(); output.flush(); output.close(); scaledImage = null; } if (!Files.exists(cachedFile)) { throw new Exception("unable to cache file: " + originalFile); } return cachedFile; }
From source file:org.geowebcache.layer.MetaTile.java
/** * Outputs one tile from the internal array of tiles to a provided stream * /*from w ww . ja v a 2 s .c om*/ * @param tileIdx * the index of the tile relative to the internal array * @param format * the Java name for the format * @param resource * the outputstream * @return true if no error was encountered * @throws IOException */ public boolean writeTileToStream(final int tileIdx, Resource target) throws IOException { if (tiles == null) { return false; } String format = responseFormat.getInternalName(); if (log.isDebugEnabled()) { log.debug("Thread: " + Thread.currentThread().getName() + " writing: " + tileIdx); } // TODO should we recycle the writers ? // GR: it'd be only a 2% perf gain according to profile Iterator<ImageWriter> it = javax.imageio.ImageIO.getImageWritersByFormatName(format); ImageWriter writer = it.next(); ImageWriteParam param = writer.getDefaultWriteParam(); if (this.formatModifier != null) { param = formatModifier.adjustImageWriteParam(param); } Rectangle tileRegion = tiles[tileIdx]; RenderedImage tile = createTile(tileRegion.x, tileRegion.y, tileRegion.width, tileRegion.height); disposeLater(tile); OutputStream outputStream = target.getOutputStream(); ImageOutputStream imgOut = new MemoryCacheImageOutputStream(outputStream); writer.setOutput(imgOut); IIOImage image = new IIOImage(tile, null, null); try { writer.write(null, image, param); } finally { imgOut.close(); writer.dispose(); } return true; }
From source file:org.yamj.core.service.file.FileStorageService.java
public void storeImage(String filename, StorageType type, BufferedImage bi, ImageFormat imageFormat, int quality) throws Exception { LOG.debug("Store {} {} image: {}", type, imageFormat, filename); String storageFileName = getStorageName(type, filename); File outputFile = new File(storageFileName); ImageWriter writer = null; FileImageOutputStream output = null; try {/*from ww w . j a v a 2 s.c om*/ if (ImageFormat.PNG == imageFormat) { ImageIO.write(bi, "png", outputFile); } else { float jpegQuality = (float) quality / 100; BufferedImage bufImage = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_RGB); bufImage.createGraphics().drawImage(bi, 0, 0, null, null); @SuppressWarnings("rawtypes") Iterator iter = ImageIO.getImageWritersByFormatName("jpeg"); writer = (ImageWriter) iter.next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality(jpegQuality); output = new FileImageOutputStream(outputFile); writer.setOutput(output); IIOImage image = new IIOImage(bufImage, null, null); writer.write(null, image, iwp); } } finally { if (writer != null) { writer.dispose(); } if (output != null) { try { output.close(); } catch (IOException ex) { LOG.trace("Failed to close stream: {}", ex.getMessage(), ex); } } } }
From source file:edu.ku.brc.specify.utilapps.ERDVisualizer.java
public void writeJPEG(File outfile, BufferedImage bufferedImage, float compressionQuality) { try {// w ww . j ava 2s. c om long start = System.currentTimeMillis(); // Find a jpeg writer ImageWriter writer = null; Iterator<?> iter = ImageIO.getImageWritersByFormatName("jpg"); if (iter.hasNext()) { writer = (ImageWriter) iter.next(); } // Prepare output file ImageOutputStream ios = ImageIO.createImageOutputStream(outfile); writer.setOutput(ios); // Set the compression quality ImageWriteParam iwparam = new MyImageWriteParam(); iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwparam.setCompressionQuality(compressionQuality); // Write the image writer.write(null, new IIOImage(bufferedImage, null, null), null); // Cleanup ios.flush(); writer.dispose(); ios.close(); System.out.println(System.currentTimeMillis() - start); } catch (IOException e) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ERDVisualizer.class, e); e.printStackTrace(); } }