List of usage examples for javax.imageio IIOImage IIOImage
public IIOImage(Raster raster, List<? extends BufferedImage> thumbnails, IIOMetadata metadata)
From source file:jails.http.converter.BufferedImageHttpMessageConverter.java
public void write(BufferedImage image, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { if (contentType == null) { contentType = getDefaultContentType(); }/*from w w w.j a v a 2 s. com*/ Assert.notNull(contentType, "Count not determine Content-Type, set one using the 'defaultContentType' property"); outputMessage.getHeaders().setContentType(contentType); ImageOutputStream imageOutputStream = null; ImageWriter imageWriter = null; try { imageOutputStream = createImageOutputStream(outputMessage.getBody()); Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByMIMEType(contentType.toString()); if (imageWriters.hasNext()) { imageWriter = imageWriters.next(); ImageWriteParam iwp = imageWriter.getDefaultWriteParam(); process(iwp); imageWriter.setOutput(imageOutputStream); imageWriter.write(null, new IIOImage(image, null, null), iwp); } else { throw new HttpMessageNotWritableException( "Could not find javax.imageio.ImageWriter for Content-Type [" + contentType + "]"); } } finally { if (imageWriter != null) { imageWriter.dispose(); } if (imageOutputStream != null) { try { imageOutputStream.close(); } catch (IOException ex) { // ignore } } } }
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 av a 2 s .com * * @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:common.utils.ImageUtils.java
public static void writeImage(BufferedImage image, float quality, OutputStream out) throws IOException { ImageWriter writer = getImageWriter(); if (writer == null) return;//from ww w.j a v a 2s . c om ImageOutputStream ios = ImageIO.createImageOutputStream(out); writer.setOutput(ios); ImageWriteParam param = writer.getDefaultWriteParam(); //JPEGImageWriteParam param = new JPEGImageWriteParam(Locale.getDefault()); //param.setOptimizeHuffmanTables(true); if (quality >= 0) { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(quality); //param.setCompressionMode(ImageWriteParam.MODE_COPY_FROM_METADATA); //param.setProgressiveMode(ImageWriteParam.MODE_DISABLED); //param.setTilingMode(ImageWriteParam.MODE_DISABLED); } writer.write(null, new IIOImage(image, null, null), param); }
From source file:com.sire.web.CajFacturaEnviadaBean.java
private void savePicture() { if (file != null) { try {//from w w w. j a v a 2s .co m BufferedImage originalImage = ImageIO.read(file.getInputstream()); BufferedImage outputImage = new BufferedImage((int) (originalImage.getWidth() * 0.25), (int) (originalImage.getHeight() * 0.25), originalImage.getType()); Graphics2D g2d = outputImage.createGraphics(); g2d.drawImage(originalImage, 0, 0, (int) (originalImage.getWidth() * 0.25), (int) (originalImage.getHeight() * 0.25), null); g2d.dispose(); String imagesFolder = System.getProperty("imagesFolder"); if (imagesFolder == null) { String currentUsersHomeDir = System.getProperty("user.home"); imagesFolder = currentUsersHomeDir + File.separator + "photos"; } Iterator iter = ImageIO.getImageWritersByFormatName("jpeg"); ImageWriter writer = (ImageWriter) iter.next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); float quality = 1.0f; // reduce quality by 0% iwp.setCompressionQuality(quality); File f = new File(imagesFolder + File.separator + fileName); try (FileImageOutputStream output = new FileImageOutputStream(f)) { writer.setOutput(output); IIOImage image = new IIOImage(outputImage, null, null); writer.write(null, image, iwp); writer.dispose(); } } catch (IOException ex) { LOGGER.severe(ex.getMessage()); } } }
From source file:com.lingxiang2014.util.ImageUtils.java
public static void addWatermark(File srcFile, File destFile, File watermarkFile, int alpha) { Assert.notNull(srcFile);/*from ww w .ja v a 2 s . c o m*/ 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:editeurpanovisu.ReadWriteImage.java
/** * * @param img//from www .j av a 2 s. c o m * @param destFile * @param sharpen * @param sharpenLevel * @throws IOException */ public static void writePng(Image img, String destFile, boolean sharpen, float sharpenLevel) throws IOException { sharpenMatrix = calculeSharpenMatrix(sharpenLevel); BufferedImage imageRGBSharpen = null; IIOImage iioImage = null; BufferedImage image = SwingFXUtils.fromFXImage(img, null); // Get buffered image. BufferedImage imageRGB = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.BITMASK); Graphics2D graphics = imageRGB.createGraphics(); graphics.drawImage(image, 0, 0, null); if (sharpen) { imageRGBSharpen = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); Kernel kernel = new Kernel(3, 3, sharpenMatrix); ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); cop.filter(imageRGB, imageRGBSharpen); } ImageWriter writer = null; FileImageOutputStream output = null; try { writer = ImageIO.getImageWritersByFormatName("png").next(); ImageWriteParam param = writer.getDefaultWriteParam(); output = new FileImageOutputStream(new File(destFile)); writer.setOutput(output); if (sharpen) { iioImage = new IIOImage(imageRGBSharpen, null, null); } else { iioImage = new IIOImage(imageRGB, null, null); } writer.write(null, iioImage, param); } catch (IOException ex) { throw ex; } finally { if (writer != null) { writer.dispose(); } if (output != null) { output.close(); } } graphics.dispose(); }
From source file:com.mirth.connect.server.util.DICOMMessageUtil.java
private static byte[] saveAsJpeg(ImagePlus imagePlug, int quality) { int imageType = BufferedImage.TYPE_INT_RGB; if (imagePlug.getProcessor().isDefaultLut()) { imageType = BufferedImage.TYPE_BYTE_GRAY; }/*from w ww . ja va 2 s .c o m*/ BufferedImage bufferedImage = new BufferedImage(imagePlug.getWidth(), imagePlug.getHeight(), imageType); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { Graphics graphics = bufferedImage.createGraphics(); graphics.drawImage(imagePlug.getImage(), 0, 0, null); graphics.dispose(); ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); writer.setOutput(ImageIO.createImageOutputStream(baos)); ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(quality / 100f); if (quality == 100) { param.setSourceSubsampling(1, 1, 0, 0); } IIOImage iioImage = new IIOImage(bufferedImage, null, null); writer.write(null, iioImage, param); return baos.toByteArray(); } catch (Exception e) { logger.error("Error Converting DICOM image", e); } finally { IOUtils.closeQuietly(baos); } return null; }
From source file:com.db.comserv.main.utilities.HttpCaller.java
public static String compress(String imageString, float quality) throws IOException { byte[] imageByte = Base64.decodeBase64(imageString); ByteArrayInputStream bis = new ByteArrayInputStream(imageByte); BufferedImage image = ImageIO.read(bis); bis.close();//from w ww. ja v a2 s . c o m // Get a ImageWriter for given extension format. Iterator<ImageWriter> writers = ImageIO.getImageWritersBySuffix("jpg"); if (!writers.hasNext()) throw new IllegalStateException("No writers found"); ImageWriter writer = (ImageWriter) writers.next(); // Create the ImageWriteParam to compress the image. ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(quality); // The output will be a ByteArrayOutputStream (in memory) ByteArrayOutputStream bos = new ByteArrayOutputStream(32768); ImageOutputStream ios = ImageIO.createImageOutputStream(bos); writer.setOutput(ios); writer.write(null, new IIOImage(image, null, null), param); ios.flush(); // otherwise the buffer size will be zero! byte[] encodedBytes = Base64.encodeBase64(bos.toByteArray()); return new String(encodedBytes); }
From source file:net.intelliant.util.UtilCommon.java
private static String generateCompressedImageForInputFile(String locationInFileSystem, String srcFileName) throws NoSuchAlgorithmException, IOException { String outputFileName = srcFileName; File srcFile = new File(locationInFileSystem, srcFileName); File compressedFile = null;/*ww w .j a va 2 s .c o m*/ FileImageOutputStream outputStream = null; try { if (srcFile.exists()) { String md5sum = getMD5SumForFile(srcFile.getAbsolutePath()); int extentionIndex = srcFileName.lastIndexOf("."); // find index of extension. if (extentionIndex != -1) { outputFileName = outputFileName.replaceFirst("\\.", "_" + md5sum + "."); } compressedFile = new File(locationInFileSystem, outputFileName); if (Debug.infoOn()) { Debug.logInfo("[generateCompressedImageFor] sourceFile >> " + srcFile.getAbsolutePath(), module); Debug.logInfo("[generateCompressedImageFor] md5sum >> " + md5sum, module); Debug.logInfo( "[generateCompressedImageFor] compressedFile >> " + compressedFile.getAbsolutePath(), module); } if (!compressedFile.exists()) { if (Debug.infoOn()) { Debug.logInfo("[generateCompressedImageFor] compressed file does NOT exist..", module); } Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg"); ImageWriter imageWriter = (ImageWriter) iter.next(); ImageWriteParam iwp = imageWriter.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality(Float.parseFloat(imageCompressionQuality)); // an integer between 0 and 1, 1 specifies minimum compression and maximum quality BufferedImage bufferedImage = ImageIO.read(srcFile); outputStream = new FileImageOutputStream(compressedFile); imageWriter.setOutput(outputStream); IIOImage image = new IIOImage(bufferedImage, null, null); imageWriter.write(null, image, iwp); } else { if (Debug.infoOn()) { Debug.logInfo( "[generateCompressedImageFor] compressed file exists, not compressing again..", module); } } } else { Debug.logWarning(String.format("Source image file does NOT exist..", srcFile), module); } } finally { if (outputStream != null) { outputStream.close(); outputStream = null; } } return outputFileName; }
From source file:de.inren.service.picture.PictureModificationServiceImpl.java
private void writeJpeg(BufferedImage image, File file, float quality) throws IOException { ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality(quality);// w ww. ja va 2 s . c o m FileImageOutputStream output = new FileImageOutputStream(file); writer.setOutput(output); writer.write(null, new IIOImage(image, null, null), iwp); }