List of usage examples for javax.imageio ImageWriter setOutput
public void setOutput(Object output)
From source file:it.geosolutions.imageio.plugins.nitronitf.ImageIOUtils.java
/** * Returns an ImageWriter given the input file * /*ww w . jav a2 s. c om*/ * @param file * @return * @throws IOException */ public static ImageWriter getImageWriter(File file) throws IOException { String ext = FilenameUtils.getExtension(file.getName().toLowerCase()); ImageWriter writer = null; Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersBySuffix(ext); if (imageWriters.hasNext()) { writer = imageWriters.next(); ImageOutputStream stream = ImageIO.createImageOutputStream(file); writer.setOutput(stream); } return writer; }
From source file:editeurpanovisu.ReadWriteImage.java
/** * * @param img//from www. j av a2s . c om * @param destFile * @param quality * @param sharpen * @param sharpenLevel * @throws IOException */ public static void writeJpeg(Image img, String destFile, float quality, 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.OPAQUE); // Remove alpha-channel from buffered image. 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("jpeg").next(); ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(quality); 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:net.rptools.tokentool.AppActions.java
public static void saveToken(File rptok_file, boolean overwrite) { if (rptok_file != null) { if (!rptok_file.getName().toUpperCase().endsWith(".RPTOK")) { rptok_file = new File(rptok_file.getAbsolutePath() + ".rptok"); }/* ww w. j a va2s . c o m*/ if (rptok_file.exists() && !overwrite) { if (!TokenTool.confirm("File exists. Overwrite?")) { return; } else { rptok_file.delete(); } } String tokenName = FilenameUtils.removeExtension(rptok_file.getName()); try { // Write out the token image first or aka POG image. File tokenImageFile = File.createTempFile("tokenImage", ".png"); // PW: This code addes the pHYs chunk to the // output png file with X & Y dpi set. BufferedImage tokenImg = TokenTool.getFrame().getComposedToken(); BufferedImage portraitImg = TokenTool.getFrame().getTokenCompositionPanel().getBaseImage(); ImageWriter writer = getImageWriterBySuffix("png"); // Created object for outputStream so we can properly close it! No longer locks .png files until app closes! ImageOutputStream ios = ImageIO.createImageOutputStream(tokenImageFile); writer.setOutput(ios); ImageWriteParam param = writer.getDefaultWriteParam(); PNGMetadata png = new PNGMetadata(); // 39.375 inches per meter // I'm using the image width for the DPI under // the assumption that the token fits within // one cell. int resX = (int) (tokenImg.getWidth() * 39.375f); png.pHYs_pixelsPerUnitXAxis = resX; png.pHYs_pixelsPerUnitYAxis = resX; png.pHYs_unitSpecifier = 1; // Meters - alternative is "unknown" png.pHYs_present = true; writer.write(null, new IIOImage(tokenImg, null, png), param); ios.close(); // Now write out the Portrait image, here we'll use JPEG to save space File portraitImageFile = File.createTempFile("portraitImage", ".jpg"); writer.reset(); writer = getImageWriterBySuffix("jpg"); ios = ImageIO.createImageOutputStream(portraitImageFile); writer.setOutput(ios); param = writer.getDefaultWriteParam(); writer.write(null, new IIOImage(portraitImg, null, null), param); writer.dispose(); ios.close(); // Lets create the token! Token _token = new Token(); Asset tokenImage = null; tokenImage = AssetManager.createAsset(tokenImageFile); AssetManager.putAsset(tokenImage); _token = new Token(tokenName, tokenImage.getId()); _token.setGMName(tokenName); // Jamz: Below calls not needed, creates extra entries in XML preventing token image from changing inside MapTool //_token.setImageAsset(tokenImage.getName()); //_token.setImageAsset(tokenImage.getName(), tokenImage.getId()); // set the image shape Image image = ImageIO.read(tokenImageFile); _token.setShape(TokenUtil.guessTokenType(image)); // set the height/width, fixes dragging to stamp layer issue _token.setHeight(tokenImg.getHeight()); _token.setWidth(tokenImg.getWidth()); // set the portrait image asset Asset portrait = AssetManager.createAsset(portraitImageFile); // Change for portrait AssetManager.putAsset(portrait); _token.setPortraitImage(portrait.getId()); // Time to write out the .rptok token file... PackedFile pakFile = null; try { pakFile = new PackedFile(rptok_file); saveAssets(_token.getAllImageAssets(), pakFile); pakFile.setContent(_token); BufferedImage thumb = ImageUtil.createCompatibleImage(image, THUMB_SIZE, THUMB_SIZE, null); pakFile.putFile(FILE_THUMBNAIL, ImageUtil.imageToBytes(thumb, "png")); pakFile.setProperty(PROP_VERSION, TokenToolFrame.VERSION); pakFile.save(); } catch (Exception e) { e.printStackTrace(); } finally { if (pakFile != null) pakFile.close(); tokenImageFile.delete(); portraitImageFile.delete(); } } catch (IOException ioe) { ioe.printStackTrace(); TokenTool.showError("Unable to write image: " + ioe); } } }
From source file:org.hippoecm.frontend.plugins.gallery.imageutil.ImageUtils.java
/** * Returns the data of a {@link BufferedImage} as a binary output stream. If the image is <code>null</code>, * a stream of zero bytes is returned.//from ww w . ja v a2 s. com * * @param writer the writer to use for writing the image data. * @param image the image to write. * @param compressionQuality a float between 0 and 1 that indicates the desired compression quality. Values lower than * 0 will be interpreted as 0, values higher than 1 will be interpreted as 1. * * @return an output stream with the data of the given image. * * @throws IOException when creating the binary output stream failed. */ public static ByteArrayOutputStream writeImage(ImageWriter writer, BufferedImage image, float compressionQuality) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); if (image != null) { ImageOutputStream ios = null; try { ios = ImageIO.createImageOutputStream(out); writer.setOutput(ios); // write compressed images with high quality final ImageWriteParam writeParam = writer.getDefaultWriteParam(); if (writeParam.canWriteCompressed()) { String[] compressionTypes = writeParam.getCompressionTypes(); if (compressionTypes != null && compressionTypes.length > 0) { writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); writeParam.setCompressionType(compressionTypes[0]); // ensure a compression quality between 0 and 1 float trimmedCompressionQuality = Math.max(compressionQuality, 0); trimmedCompressionQuality = Math.min(trimmedCompressionQuality, 1f); writeParam.setCompressionQuality(trimmedCompressionQuality); } } final IIOImage iioImage = new IIOImage(image, null, null); writer.write(null, iioImage, writeParam); ios.flush(); } finally { if (ios != null) { ios.close(); } } } return out; }
From source file:ImageUtil.java
/** * store BufferedImage to file/* w w w.j a v a 2 s . c o m*/ * @param image BufferedImage * @param outputFile output image file * @param quality quality of output image * @return true success, else fail */ public static boolean storeImage(BufferedImage image, File outputFile, float quality) { try { //reconstruct folder structure for image file output if (outputFile.getParentFile() != null && !outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } if (outputFile.exists()) { outputFile.delete(); } //get image file suffix String extName = "png"; //get registry ImageWriter for specified image suffix Iterator writers = ImageIO.getImageWritersByFormatName(extName); ImageWriter imageWriter = (ImageWriter) writers.next(); //set image output params ImageWriteParam params = new JPEGImageWriteParam(null); params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); params.setCompressionQuality(quality); params.setProgressiveMode(javax.imageio.ImageWriteParam.MODE_DISABLED); params.setDestinationType(new ImageTypeSpecifier(IndexColorModel.getRGBdefault(), IndexColorModel.getRGBdefault().createCompatibleSampleModel(16, 16))); //writer image to file ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputFile); imageWriter.setOutput(imageOutputStream); imageWriter.write(null, new IIOImage(image, null, null), params); imageOutputStream.close(); imageWriter.dispose(); return true; } catch (Exception e) { e.printStackTrace(); } return false; }
From source file:com.sketchy.utils.image.SketchyImage.java
public static void save(SketchyImage sketchyImage, File file) throws Exception { if (!file.getParentFile().canWrite()) { throw new Exception("Can not write to File: " + file.getPath() + "!"); }/*w w w . j a v a 2 s .co m*/ if (!StringUtils.endsWithIgnoreCase(file.getName(), ".png")) { throw new Exception("Can not save SketchyImage! Must be a .png file!"); } Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName("png"); ImageWriter imageWriter = null; if (imageWriters.hasNext()) { // Just get first one imageWriter = imageWriters.next(); } if (imageWriter == null) { // this should never happen!! if so.. we got problems throw new Exception("Can not find ImageReader for .png Files!"); } ImageOutputStream os = null; try { os = ImageIO.createImageOutputStream(file); imageWriter.setOutput(os); ImageWriteParam imageWriterParam = imageWriter.getDefaultWriteParam(); IIOMetadata metadata = imageWriter.getDefaultImageMetadata( ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_BINARY), imageWriterParam); String metaDataFormatName = metadata.getNativeMetadataFormatName(); IIOMetadataNode metaDataNode = (IIOMetadataNode) metadata.getAsTree(metaDataFormatName); NodeList childNodes = metaDataNode.getElementsByTagName("pHYs"); IIOMetadataNode physNode = null; if (childNodes.getLength() == 0) { physNode = new IIOMetadataNode("pHYs"); physNode.setAttribute("pixelsPerUnitXAxis", Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterWidth * 1000))); physNode.setAttribute("pixelsPerUnitYAxis", Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterHeight * 1000))); physNode.setAttribute("unitSpecifier", "meter"); // always meter metaDataNode.appendChild(physNode); } else { for (int nodeIdx = 0; nodeIdx < childNodes.getLength(); nodeIdx++) { physNode = (IIOMetadataNode) childNodes.item(nodeIdx); physNode.setAttribute("pixelsPerUnitXAxis", Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterWidth * 1000))); physNode.setAttribute("pixelsPerUnitYAxis", Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterHeight * 1000))); physNode.setAttribute("unitSpecifier", "meter"); // always meter metaDataNode.appendChild(physNode); } } metadata.setFromTree(metaDataFormatName, metaDataNode); imageWriter.write(new IIOImage(sketchyImage.image, null, metadata)); os.flush(); } catch (Exception e) { throw new Exception("Error Saving SketchyImage File: " + file.getPath() + "! " + e.getMessage()); } finally { IOUtils.closeQuietly(os); } }
From source file:ch.rasc.downloadchart.DownloadChartServlet.java
private static void handleJpg(HttpServletResponse response, byte[] imageData, Integer width, Integer height, String filename, JpegOptions options) throws IOException { response.setContentType("image/jpeg"); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".jpg\";"); BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageData)); Dimension newDimension = calculateDimension(image, width, height); int imgWidth = image.getWidth(); int imgHeight = image.getHeight(); if (newDimension != null) { imgWidth = newDimension.width;/*from w w w .jav a2 s . c om*/ imgHeight = newDimension.height; } BufferedImage newImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g = newImage.createGraphics(); g.drawImage(image, 0, 0, imgWidth, imgHeight, Color.BLACK, null); g.dispose(); if (newDimension != null) { g.setComposite(AlphaComposite.Src); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } try (ImageOutputStream ios = ImageIO.createImageOutputStream(response.getOutputStream())) { Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg"); ImageWriter writer = iter.next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); if (options != null && options.quality != null && options.quality != 0 && options.quality != 100) { iwp.setCompressionQuality(options.quality / 100f); } else { iwp.setCompressionQuality(1); } writer.setOutput(ios); writer.write(null, new IIOImage(newImage, null, null), iwp); writer.dispose(); } }
From source file:org.forgerock.doc.maven.PNGUtils.java
private static void saveBufferedImage(final BufferedImage bufferedImage, final File outputFile, final int dotsPerInch) throws IOException { for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName("png"); iw.hasNext();) { ImageWriter writer = iw.next(); ImageWriteParam writeParam = writer.getDefaultWriteParam(); ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier .createFromBufferedImageType(BufferedImage.TYPE_INT_RGB); IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam); if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) { continue; }/*from w ww . ja v a2s.c om*/ setDPI(metadata, dotsPerInch); final ImageOutputStream stream = ImageIO.createImageOutputStream(outputFile); try { writer.setOutput(stream); writer.write(metadata, new IIOImage(bufferedImage, null, metadata), writeParam); } finally { stream.close(); } break; } }
From source file:eu.europa.esig.dss.pades.signature.visible.ImageFactory.java
private static InputStream convertToInputStream(BufferedImage buffImage, int dpi) throws IOException { Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName("jpeg"); if (!it.hasNext()) { throw new DSSException("No writer for JPEG found"); }//from www .ja va 2 s. c om ImageWriter writer = it.next(); JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) writer.getDefaultWriteParam(); jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT); jpegParams.setCompressionQuality(1); ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier .createFromBufferedImageType(BufferedImage.TYPE_INT_RGB); IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, jpegParams); initDpi(metadata, dpi); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageOutputStream imageOs = ImageIO.createImageOutputStream(os); writer.setOutput(imageOs); writer.write(metadata, new IIOImage(buffImage, null, metadata), jpegParams); InputStream is = new ByteArrayInputStream(os.toByteArray()); return is; }
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 w w. j av 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); }