Java Code Examples for javax.imageio.ImageWriter#write()
The following examples show how to use
javax.imageio.ImageWriter#write() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImageHelper.java From olat with Apache License 2.0 | 6 votes |
/** * Can change this to choose a better compression level as the default * * @param image * @param scaledImage * @return */ private static boolean writeTo(BufferedImage image, OutputStream scaledImage, Size scaledSize, String outputFormat) { try { if (!StringHelper.containsNonWhitespace(outputFormat)) { outputFormat = OUTPUT_FORMAT; } Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(outputFormat); if (writers.hasNext()) { ImageWriter writer = writers.next(); ImageWriteParam iwp = getOptimizedImageWriteParam(writer, scaledSize); IIOImage iiOImage = new IIOImage(image, null, null); ImageOutputStream iOut = new MemoryCacheImageOutputStream(scaledImage); writer.setOutput(iOut); writer.write(null, iiOImage, iwp); writer.dispose(); iOut.flush(); iOut.close(); return true; } else { return ImageIO.write(image, outputFormat, scaledImage); } } catch (IOException e) { return false; } }
Example 2
Source File: ImageIOHelper.java From JewelCrawler with GNU General Public License v3.0 | 6 votes |
public static File createImage(BufferedImage bi) { File tempFile = null; try { tempFile = File.createTempFile("tempImageFile", ".tif"); tempFile.deleteOnExit(); TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US); tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED); // Get tif writer and set output to file Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("tiff"); ImageWriter writer = writers.next(); IIOImage image = new IIOImage(bi, null, null); tempFile = tempImageFile(tempFile); ImageOutputStream ios = ImageIO.createImageOutputStream(tempFile); writer.setOutput(ios); writer.write(null, image, tiffWriteParam); ios.close(); writer.dispose(); } catch (Exception exc) { exc.printStackTrace(); } return tempFile; }
Example 3
Source File: ImageTools.java From MtgDesktopCompanion with GNU General Public License v3.0 | 6 votes |
public static void saveImageInPng(BufferedImage img, File f) throws IOException { Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName("png"); if(!iw.hasNext()) throw new IOException("PNG Writer not found"); ImageWriter writer = iw.next(); ImageWriteParam writeParam = writer.getDefaultWriteParam(); ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB); IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam); setDPI(metadata); ImageOutputStream stream = ImageIO.createImageOutputStream(f); try { writer.setOutput(stream); writer.write(metadata, new IIOImage(img, null, metadata), writeParam); } finally { stream.close(); } }
Example 4
Source File: ShortHistogramTest.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
protected File writeImageWithHist(BufferedImage bi) throws IOException { File f = File.createTempFile("hist_", ".png", new File(".")); ImageWriter writer = ImageIO.getImageWritersByFormatName("PNG").next(); ImageOutputStream ios = ImageIO.createImageOutputStream(f); writer.setOutput(ios); ImageWriteParam param = writer.getDefaultWriteParam(); ImageTypeSpecifier type = new ImageTypeSpecifier(bi); IIOMetadata imgMetadata = writer.getDefaultImageMetadata(type, param); /* add hIST node to image metadata */ imgMetadata = upgradeMetadata(imgMetadata, bi); IIOImage iio_img = new IIOImage(bi, null, // no thumbnails imgMetadata); writer.write(iio_img); ios.flush(); ios.close(); return f; }
Example 5
Source File: ShortHistogramTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
protected File writeImageWithHist(BufferedImage bi) throws IOException { File f = File.createTempFile("hist_", ".png", new File(".")); ImageWriter writer = ImageIO.getImageWritersByFormatName("PNG").next(); ImageOutputStream ios = ImageIO.createImageOutputStream(f); writer.setOutput(ios); ImageWriteParam param = writer.getDefaultWriteParam(); ImageTypeSpecifier type = new ImageTypeSpecifier(bi); IIOMetadata imgMetadata = writer.getDefaultImageMetadata(type, param); /* add hIST node to image metadata */ imgMetadata = upgradeMetadata(imgMetadata, bi); IIOImage iio_img = new IIOImage(bi, null, // no thumbnails imgMetadata); writer.write(iio_img); ios.flush(); ios.close(); return f; }
Example 6
Source File: AnnotateScreenCapture.java From marathonv5 with Apache License 2.0 | 5 votes |
private void writePNG(File file) throws IOException, FileNotFoundException { ImageWriter writer = getPNGImageWriter(); ImageOutputStream ios = ImageIO.createImageOutputStream(new FileOutputStream(file)); writer.setOutput(ios); BufferedImage image = imagePanel.getImage(); updateAnnotations(image); writer.write(image); writer.dispose(); }
Example 7
Source File: Images.java From restcommander with Apache License 2.0 | 5 votes |
/** * Crop an image * @param originalImage The image file * @param to The destination file * @param x1 The new x origin * @param y1 The new y origin * @param x2 The new x end * @param y2 The new y end */ public static void crop(File originalImage, File to, int x1, int y1, int x2, int y2) { try { BufferedImage source = ImageIO.read(originalImage); String mimeType = "image/jpeg"; if (to.getName().endsWith(".png")) { mimeType = "image/png"; } if (to.getName().endsWith(".gif")) { mimeType = "image/gif"; } int width = x2 - x1; int height = y2 - y1; // out BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Image croppedImage = source.getSubimage(x1, y1, width, height); Graphics graphics = dest.getGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, width, height); graphics.drawImage(croppedImage, 0, 0, null); ImageWriter writer = ImageIO.getImageWritersByMIMEType(mimeType).next(); ImageWriteParam params = writer.getDefaultWriteParam(); writer.setOutput(new FileImageOutputStream(to)); IIOImage image = new IIOImage(dest, null, null); writer.write(null, image, params); } catch (Exception e) { throw new RuntimeException(e); } }
Example 8
Source File: TopDownTest.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
private static void writeWithCompression(BufferedImage src, String compression) throws IOException { System.out.println("Compression: " + compression); ImageWriter writer = ImageIO.getImageWritersByFormatName("BMP").next(); if (writer == null) { throw new RuntimeException("Test failed: no bmp writer available"); } File fout = File.createTempFile(compression + "_", ".bmp", new File(".")); ImageOutputStream ios = ImageIO.createImageOutputStream(fout); writer.setOutput(ios); BMPImageWriteParam param = (BMPImageWriteParam) writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionType(compression); param.setTopDown(true); writer.write(null, new IIOImage(src, null, null), param); writer.dispose(); ios.flush(); ios.close(); BufferedImage dst = ImageIO.read(fout); verify(dst); }
Example 9
Source File: JPEGMovWriter.java From pumpernickel with MIT License | 5 votes |
@Override protected void writeFrame(OutputStream out, BufferedImage image, Map<String, Object> settings) throws IOException { if (image.getType() == BufferedImage.TYPE_INT_ARGB || image.getType() == BufferedImage.TYPE_INT_ARGB_PRE) { if (printWarning == false) { printWarning = true; System.err .println("JPEGMovWriter Warning: a BufferedImage of type TYPE_INT_ARGB may produce unexpected results. The recommended type is TYPE_INT_RGB."); } } float quality; if (settings != null && settings.get(PROPERTY_QUALITY) instanceof Number) { quality = ((Number) settings.get(PROPERTY_QUALITY)).floatValue(); } else if (settings != null && settings.get(PROPERTY_QUALITY) instanceof String) { quality = Float.parseFloat((String) settings.get(PROPERTY_QUALITY)); } else { quality = defaultQuality; } MemoryCacheImageOutputStream iOut = new MemoryCacheImageOutputStream( out); ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/jpeg").next(); ImageWriteParam iwParam = iw.getDefaultWriteParam(); iwParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwParam.setCompressionQuality(quality); iw.setOutput(iOut); IIOImage img = new IIOImage(image, null, null); iw.write(null, img, iwParam); }
Example 10
Source File: JpegOutput.java From Pixelitor with GNU General Public License v3.0 | 5 votes |
private static void writeJPGtoStream(BufferedImage image, ImageInputStream ios, JpegInfo config, ProgressTracker tracker) throws IOException { Iterator<ImageWriter> jpgWriters = ImageIO.getImageWritersByFormatName("jpg"); if (!jpgWriters.hasNext()) { throw new IllegalStateException("No JPG writers found"); } ImageWriter writer = jpgWriters.next(); ImageWriteParam imageWriteParam = writer.getDefaultWriteParam(); if (config.isProgressive()) { imageWriteParam.setProgressiveMode(MODE_DEFAULT); } else { imageWriteParam.setProgressiveMode(MODE_DISABLED); } imageWriteParam.setCompressionMode(MODE_EXPLICIT); imageWriteParam.setCompressionQuality(config.getQuality()); IIOImage iioImage = new IIOImage(image, null, null); writer.setOutput(ios); if (tracker != null) { writer.addIIOWriteProgressListener(new TrackerWriteProgressListener(tracker)); } writer.write(null, iioImage, imageWriteParam); ios.flush(); ios.close(); }
Example 11
Source File: WebPWriterTest.java From webp-imageio with Apache License 2.0 | 5 votes |
/** * Test method tests {@link WebPWriter} with image resize options. * * @throws IOException * the test fails. */ @Test(dataProvider = "createImagesWithScaleOptions", enabled = true) public void testImageWriterScale(final RenderedImage image, final float xScale, final float yScale, final String outputName) throws IOException { final String extension = outputName.substring(outputName.lastIndexOf(".") + 1); // Scale the image. final RenderedOp scaledImage = ScaleDescriptor.create(image, xScale, yScale, 0f, 0f, Interpolation.getInstance(Interpolation.INTERP_BICUBIC_2), null); // get writer final ImageWriter imgWriter = ImageIO.getImageWritersByFormatName(extension).next(); final ImageWriteParam imgWriteParams = new WebPWriteParam(null); final String testName = "ScaleOptions"; final File file = createOutputFile(testName, outputName); final ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(file); try { imgWriter.setOutput(imageOutputStream); imgWriter.write(null, new IIOImage(scaledImage, null, null), imgWriteParams); final int length = (int) imageOutputStream.length(); assertTrue(length > 0); } finally { try { imageOutputStream.close(); } catch (final IOException e) { } } }
Example 12
Source File: DwFrameCapture.java From PixelFlow with MIT License | 5 votes |
public void save(){ try { BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(filename)); ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next(); ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(jpeg_compression); writer.setOutput(ImageIO.createImageOutputStream(output)); writer.write(null, new IIOImage(img, null, null), param); writer.dispose(); output.flush(); output.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // try { // BufferedOutputStream imageOutputStream = new BufferedOutputStream(new FileOutputStream(filename)); // ImageIO.write(img, "JPG", imageOutputStream); // imageOutputStream.close(); // } catch (IOException e) { // e.printStackTrace(); // } }
Example 13
Source File: CompressionModeTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private static void doTest(int mode) { String fileFormat = "bmp"; try { ImageWriter iw = (ImageWriter)ImageIO.getImageWritersBySuffix(fileFormat).next(); if(iw == null) { throw new RuntimeException("No available image writer for " + fileFormat + " Test failed."); } File file = new File("image." + fileFormat); ImageOutputStream ios = ImageIO.createImageOutputStream(file); iw.setOutput(ios); BufferedImage bimg = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); Graphics g = bimg.getGraphics(); g.setColor(Color.green); g.fillRect(0,0,100,100); ImageWriteParam param = iw.getDefaultWriteParam(); param.setCompressionMode(mode); IIOMetadata meta = iw.getDefaultImageMetadata(new ImageTypeSpecifier(bimg), param); IIOImage iioImg = new IIOImage(bimg, null, meta); iw.write(null, iioImg, param); } catch(Exception e) { e.printStackTrace(); throw new RuntimeException("Test failed."); } }
Example 14
Source File: TopDownTest.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
private static void writeWithCompression(BufferedImage src, String compression) throws IOException { System.out.println("Compression: " + compression); ImageWriter writer = ImageIO.getImageWritersByFormatName("BMP").next(); if (writer == null) { throw new RuntimeException("Test failed: no bmp writer available"); } File fout = File.createTempFile(compression + "_", ".bmp", new File(".")); ImageOutputStream ios = ImageIO.createImageOutputStream(fout); writer.setOutput(ios); BMPImageWriteParam param = (BMPImageWriteParam) writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionType(compression); param.setTopDown(true); writer.write(null, new IIOImage(src, null, null), param); writer.dispose(); ios.flush(); ios.close(); BufferedImage dst = ImageIO.read(fout); verify(dst); }
Example 15
Source File: ITXtTest.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
private static void writeTo(File f, ITXtTest t) { BufferedImage src = createBufferedImage(); try { ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(f); ImageTypeSpecifier imageTypeSpecifier = new ImageTypeSpecifier(src); ImageWriter imageWriter = ImageIO.getImageWritersByFormatName("PNG").next(); imageWriter.setOutput(imageOutputStream); IIOMetadata m = imageWriter.getDefaultImageMetadata(imageTypeSpecifier, null); String format = m.getNativeMetadataFormatName(); Node root = m.getAsTree(format); IIOMetadataNode iTXt = t.getNode(); root.appendChild(iTXt); m.setFromTree(format, root); imageWriter.write(new IIOImage(src, null, m)); imageOutputStream.close(); System.out.println("Writing done."); } catch (Throwable e) { throw new RuntimeException("Writing test failed.", e); } }
Example 16
Source File: RuntimeBuiltinLeafInfoImpl.java From hottub with GNU General Public License v2.0 | 5 votes |
public Base64Data print(Image v) { ByteArrayOutputStreamEx imageData = new ByteArrayOutputStreamEx(); XMLSerializer xs = XMLSerializer.getInstance(); String mimeType = xs.getXMIMEContentType(); if(mimeType==null || mimeType.startsWith("image/*")) // because PNG is lossless, it's a good default // // mime type can be a range, in which case we can't just pass that // to ImageIO.getImageWritersByMIMEType, so here I'm just assuming // the default of PNG. Not sure if this is complete. mimeType = "image/png"; try { Iterator<ImageWriter> itr = ImageIO.getImageWritersByMIMEType(mimeType); if(itr.hasNext()) { ImageWriter w = itr.next(); ImageOutputStream os = ImageIO.createImageOutputStream(imageData); w.setOutput(os); w.write(convertToBufferedImage(v)); os.close(); w.dispose(); } else { // no encoder xs.handleEvent(new ValidationEventImpl( ValidationEvent.ERROR, Messages.NO_IMAGE_WRITER.format(mimeType), xs.getCurrentLocation(null) )); // TODO: proper error reporting throw new RuntimeException("no encoder for MIME type "+mimeType); } } catch (IOException e) { xs.handleError(e); // TODO: proper error reporting throw new RuntimeException(e); } Base64Data bd = new Base64Data(); imageData.set(bd,mimeType); return bd; }
Example 17
Source File: BooleanAttributes.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
public static void test(String mimeType, boolean useStreamMeta, String metaXml, String... boolXpaths) throws Exception { BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB); ImageWriter iw = ImageIO.getImageWritersByMIMEType(mimeType).next(); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageOutputStream ios = new MemoryCacheImageOutputStream(os); iw.setOutput(ios); ImageWriteParam param = null; IIOMetadata streamMeta = iw.getDefaultStreamMetadata(param); IIOMetadata imageMeta = iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), param); IIOMetadata meta = useStreamMeta ? streamMeta : imageMeta; Source src = new StreamSource(new StringReader(metaXml)); DOMResult dst = new DOMResult(); transform(src, dst); Document doc = (Document)dst.getNode(); Element node = doc.getDocumentElement(); String metaFormat = node.getNodeName(); // Verify that the default metadata gets formatted correctly. verify(meta.getAsTree(metaFormat), boolXpaths, false); meta.mergeTree(metaFormat, node); // Verify that the merged metadata gets formatte correctly. verify(meta.getAsTree(metaFormat), boolXpaths, true); iw.write(streamMeta, new IIOImage(img, null, imageMeta), param); iw.dispose(); ios.close(); ImageReader ir = ImageIO.getImageReader(iw); byte[] bytes = os.toByteArray(); if (bytes.length == 0) throw new AssertionError("Zero length image file"); ByteArrayInputStream is = new ByteArrayInputStream(bytes); ImageInputStream iis = new MemoryCacheImageInputStream(is); ir.setInput(iis); if (useStreamMeta) meta = ir.getStreamMetadata(); else meta = ir.getImageMetadata(0); // Verify again after writing and re-reading the image verify(meta.getAsTree(metaFormat), boolXpaths, true); }
Example 18
Source File: BooleanAttributes.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 4 votes |
public static void test(String mimeType, boolean useStreamMeta, String metaXml, String... boolXpaths) throws Exception { BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB); ImageWriter iw = ImageIO.getImageWritersByMIMEType(mimeType).next(); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageOutputStream ios = new MemoryCacheImageOutputStream(os); iw.setOutput(ios); ImageWriteParam param = null; IIOMetadata streamMeta = iw.getDefaultStreamMetadata(param); IIOMetadata imageMeta = iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), param); IIOMetadata meta = useStreamMeta ? streamMeta : imageMeta; Source src = new StreamSource(new StringReader(metaXml)); DOMResult dst = new DOMResult(); transform(src, dst); Document doc = (Document)dst.getNode(); Element node = doc.getDocumentElement(); String metaFormat = node.getNodeName(); // Verify that the default metadata gets formatted correctly. verify(meta.getAsTree(metaFormat), boolXpaths, false); meta.mergeTree(metaFormat, node); // Verify that the merged metadata gets formatte correctly. verify(meta.getAsTree(metaFormat), boolXpaths, true); iw.write(streamMeta, new IIOImage(img, null, imageMeta), param); iw.dispose(); ios.close(); ImageReader ir = ImageIO.getImageReader(iw); byte[] bytes = os.toByteArray(); if (bytes.length == 0) throw new AssertionError("Zero length image file"); ByteArrayInputStream is = new ByteArrayInputStream(bytes); ImageInputStream iis = new MemoryCacheImageInputStream(is); ir.setInput(iis); if (useStreamMeta) meta = ir.getStreamMetadata(); else meta = ir.getImageMetadata(0); // Verify again after writing and re-reading the image verify(meta.getAsTree(metaFormat), boolXpaths, true); }
Example 19
Source File: Pencode.java From warp10-platform with Apache License 2.0 | 4 votes |
@Override public Object apply(WarpScriptStack stack) throws WarpScriptException { Object top = stack.pop(); if (!(top instanceof processing.core.PGraphics)) { throw new WarpScriptException(getName() + " operates on a PGraphics instance."); } processing.core.PGraphics pg = (processing.core.PGraphics) top; pg.endDraw(); BufferedImage bimage = new BufferedImage(pg.pixelWidth, pg.pixelHeight, BufferedImage.TYPE_INT_ARGB); bimage.setRGB(0, 0, pg.pixelWidth, pg.pixelHeight, pg.pixels, 0, pg.pixelWidth); Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("png"); ImageWriter writer = null; if (iter.hasNext()) { writer = iter.next(); } ImageWriteParam param = writer.getDefaultWriteParam(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream output = new BufferedOutputStream(baos); try { writer.setOutput(ImageIO.createImageOutputStream(output)); writer.write(null, new IIOImage(bimage, null, null), param); } catch (IOException ioe) { throw new WarpScriptException(getName() + " error while encoding PGraphics.", ioe); } writer.dispose(); StringBuilder sb = new StringBuilder("data:image/png;base64,"); sb.append(Base64.encodeBase64String(baos.toByteArray())); stack.push(sb.toString()); // // Re-issue a 'beginDraw' so we can continue using the PGraphics instance // pg.beginDraw(); return stack; }
Example 20
Source File: WriteAbortTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
public WriteAbortTest(String format) throws Exception { try { System.out.println("Test for format " + format); bimg = new BufferedImage(width, heght, BufferedImage.TYPE_INT_RGB); Graphics2D g = bimg.createGraphics(); g.setColor(srccolor); g.fillRect(0, 0, width, heght); g.dispose(); file = File.createTempFile("src_", "." + format, new File(".")); ImageInputStream ios = ImageIO.createImageOutputStream(file); ImageWriter writer = ImageIO.getImageWritersByFormatName(format).next(); writer.setOutput(ios); writer.addIIOWriteProgressListener(this); // Abort writing in IIOWriteProgressListener.imageStarted(). startAbort = true; writer.write(bimg); startAbort = false; // Abort writing in IIOWriteProgressListener.imageProgress(). progressAbort = true; writer.write(bimg); progressAbort = false; ios.close(); /* * All abort requests from imageStarted,imageProgress * from IIOWriteProgressListener should be reached * otherwise throw RuntimeException. */ if (!(startAborted && progressAborted)) { throw new RuntimeException("All IIOWriteProgressListener abort" + " requests are not processed for format " + format); } } finally { Files.delete(file.toPath()); } }