List of usage examples for javax.imageio IIOImage IIOImage
public IIOImage(Raster raster, List<? extends BufferedImage> thumbnails, IIOMetadata metadata)
From source file:edu.ku.brc.specify.utilapps.ERDVisualizer.java
public void writeJPEG(File outfile, BufferedImage bufferedImage, float compressionQuality) { try {//from w ww. j a v a 2 s . co m 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(); } }
From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java
private IIOImage createImage(InputStream istr, int attempt) throws ImageInterpreterException { ImageInputStream iis = null;//from w w w . ja v a 2s .co m Iterator<ImageReader> ri = null; ImageReadParam param = null; ImageReader ir = null; BufferedImage bi = null; // Raster raster = null; // int[] bufferTypes = new int[] { DataBuffer.TYPE_BYTE, DataBuffer.TYPE_INT, DataBuffer.TYPE_FLOAT, DataBuffer.TYPE_DOUBLE, // DataBuffer.TYPE_SHORT, DataBuffer.TYPE_USHORT, DataBuffer.TYPE_UNDEFINED }; // Create raster from image reader try { iis = ImageIO.createImageInputStream(istr); ri = ImageIO.getImageReaders(iis); if (!ri.hasNext()) { // List<ImageReader> list = new ArrayList<ImageReader>(); // list.add(new JPEGImageReader(new JPEGImageReaderSpi())); ri = IteratorUtils.getIterator(new JPEGImageReader(new JPEGImageReaderSpi())); } } catch (IOException e) { throw new ImageInterpreterException("Error reading input stream: " + e.toString()); } while (ri.hasNext()) { ir = ri.next(); try { ir.setInput(iis); param = ir.getDefaultReadParam(); bi = ir.read(0, param); // raster = ir.readRaster(0, param); if (bi != null) { break; } } catch (Error e) { LOGGER.error("Failed to render image with ImageReader: " + e.toString()); continue; } catch (Exception e) { LOGGER.error("Failed to render image with ImageReader: " + e.toString()); continue; } } // store metadata IIOMetadata md = null; try { md = getImageMetadata(ir); } catch (ImageInterpreterException e) { LOGGER.error("Failed to extract metadata from image: " + e.getMessage()); InputStream patchedInputStream = null; if (attempt <= 1) { patchedInputStream = attempt == 0 ? new PatchInputStream(istr) : new RemoveHeaderInputStream(istr); if (istr != null) { try { istr.close(); } catch (IOException e1) { LOGGER.error("Failed to close input stream"); } } return createImage(patchedInputStream, attempt + 1); } else { LOGGER.error("Unable to read image metadata."); md = null; } } finally { if (iis != null) { try { iis.close(); } catch (IOException e) { LOGGER.error("Failed to close image stream", e); } } } // // create buffered image from raster // int count = 0; // while (count < bufferTypes.length) { // int bufferType = bufferTypes[count++]; // try { // SampleModel sm = RasterFactory.createPixelInterleavedSampleModel(bufferType, raster.getWidth(), raster.getHeight(), // raster.getNumBands()); // ColorModel cm = PlanarImage.createColorModel(sm); // // cm = bi.getColorModel(); // ColorSpace sourceColorSpace = cm.getColorSpace(); // ColorSpace destColorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB); // ColorConvertOp op = new ColorConvertOp(sourceColorSpace, destColorSpace, null); // // WritableRaster wraster = raster.createInterleavedRaster(bufferTypes[count-1], raster.getWidth(), raster.getHeight(), // raster.getNumBands(), null); // // WritableRaster wraster = op.createCompatibleDestRaster(raster); // WritableRaster wraster = op.filter(raster, null); // // Raster raster2 = bi.getRaster(); // // cm = new ComponentColorModel(cs, false, false, ColorModel.OPAQUE, bufferType); // // sm = bi.getSampleModel(); // // cm = bi.getColorModel(); // // cm = ColorModel.getRGBdefault(); // bi = new BufferedImage(cm, wraster, false, null); // cm.finalize(); // } catch (Error e) { // LOGGER.debug("Failed to render image with BufferType " + bufferType); // continue; // } catch (Exception e) { // LOGGER.debug("Failed to render image with BufferType " + bufferType); // continue; // } // break; // } if (bi == null) { throw new ImageInterpreterException("Failed to extract buffered image from image reader"); } IIOImage image = new IIOImage(bi, null, md); return image; }
From source file:lucee.runtime.img.Image.java
private void _writeOut(ImageOutputStream ios, String format, float quality, boolean noMeta) throws IOException, ExpressionException { if (quality < 0 || quality > 1) throw new IOException( "quality has an invalid value [" + quality + "], value has to be between 0 and 1"); if (StringUtil.isEmpty(format)) format = this.format; if (StringUtil.isEmpty(format)) throw new IOException("missing format"); BufferedImage im = image();/*from w w w. j a v a 2 s.c o m*/ //IIOMetadata meta = noMeta?null:metadata(format); IIOMetadata meta = noMeta ? null : getMetaData(null); ImageWriter writer = null; ImageTypeSpecifier type = ImageTypeSpecifier.createFromRenderedImage(im); Iterator<ImageWriter> iter = ImageIO.getImageWriters(type, format); if (iter.hasNext()) { writer = iter.next(); } if (writer == null) throw new IOException("no writer for format [" + format + "] available, available writer formats are [" + ListUtil.arrayToList(ImageUtil.getWriterFormatNames(), ",") + "]"); ImageWriteParam iwp = null; if ("jpg".equalsIgnoreCase(format)) { ColorModel cm = im.getColorModel(); if (cm.hasAlpha()) im = jpgImage(im); JPEGImageWriteParam jiwp = new JPEGImageWriteParam(Locale.getDefault()); jiwp.setOptimizeHuffmanTables(true); iwp = jiwp; } else iwp = writer.getDefaultWriteParam(); setCompressionModeEL(iwp, ImageWriteParam.MODE_EXPLICIT); setCompressionQualityEL(iwp, quality); writer.setOutput(ios); try { writer.write(meta, new IIOImage(im, null, meta), iwp); } finally { writer.dispose(); ios.flush(); } }
From source file:nl.softwaredesign.exporter.ODTExportFormat.java
/** * TODO Move to utility class?// www . j a v a 2 s . co 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.apache.axis2.jaxws.marshaller.impl.alt.Attachment.java
private static byte[] createBytesFromImage(Image image, String mimeType) { try {/*from w w w. j a v a 2 s . com*/ ImageWriter imageWriter = null; BufferedImage bufferedImage = (BufferedImage) image; ByteArrayOutputStream baos = new ByteArrayOutputStream(); Iterator iterator = javax.imageio.ImageIO.getImageWritersByMIMEType(mimeType); if (iterator.hasNext()) { imageWriter = (ImageWriter) iterator.next(); } ImageOutputStream ios = javax.imageio.ImageIO.createImageOutputStream(baos); imageWriter.setOutput(ios); imageWriter.write(new IIOImage(bufferedImage, null, null)); ios.flush(); imageWriter.dispose(); return baos.toByteArray(); } catch (IOException e) { throw ExceptionFactory.makeWebServiceException(e); } }
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 ww. j a va 2 s. com*/ 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:org.codice.alliance.plugin.nitf.NitfPostIngestPlugin.java
private byte[] renderToJpeg2k(final BufferedImage bufferedImage) throws IOException { BufferedImage imageToCompress = bufferedImage; if (bufferedImage.getColorModel().getNumComponents() == ARGB_COMPONENT_COUNT) { imageToCompress = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_3BYTE_BGR); Graphics2D g = imageToCompress.createGraphics(); g.drawImage(bufferedImage, 0, 0, null); }/* w w w. j a v a2 s .c o m*/ ByteArrayOutputStream os = new ByteArrayOutputStream(); J2KImageWriter writer = new J2KImageWriter(new J2KImageWriterSpi()); J2KImageWriteParam writeParams = (J2KImageWriteParam) writer.getDefaultWriteParam(); writeParams.setLossless(false); writeParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); writeParams.setCompressionType("JPEG2000"); writeParams.setCompressionQuality(0.0f); ImageOutputStream ios = new MemoryCacheImageOutputStream(os); writer.setOutput(ios); writer.write(null, new IIOImage(imageToCompress, null, null), writeParams); writer.dispose(); ios.close(); return os.toByteArray(); }
From source file:org.dcm4che.tool.dcm2jpg.Dcm2Jpg.java
private void writeImage(ImageOutputStream ios, BufferedImage bi) throws IOException { imageWriter.setOutput(ios);/*from w w w . jav a2 s . c o m*/ imageWriter.write(null, new IIOImage(bi, null, null), imageWriteParam); }
From source file:org.dcm4che2.tool.dcm2dcm.Dcm2Dcm.java
/** * Recodes the images from the source transfer syntax, as read from the src * file, to the specified destination syntax. */// www .ja va 2s .co m public void recodeImages(File src, File dest) throws IOException { ImageReader reader = new DicomImageReaderSpi().createReaderInstance(); ImageWriter writer = new DicomImageWriterSpi().createWriterInstance(); DicomStreamMetaData writeMeta = (DicomStreamMetaData) writer.getDefaultStreamMetadata(null); DicomObject ds; int frames; FileImageOutputStream output = null; try { FileImageInputStream input = new FileImageInputStream(src); try { reader.setInput(input); if (dest.exists()) dest.delete(); output = new FileImageOutputStream(dest); writer.setOutput(output); DicomStreamMetaData streamMeta = (DicomStreamMetaData) reader.getStreamMetadata(); ds = streamMeta.getDicomObject(); DicomObject newDs = new BasicDicomObject(); ds.copyTo(newDs); writeMeta.setDicomObject(newDs); frames = ds.getInt(Tag.NumberOfFrames, 1); newDs.putString(Tag.TransferSyntaxUID, VR.UI, destinationSyntax.uid()); newDs.putString(Tag.ImplementationClassUID, VR.UI, Implementation.classUID()); newDs.putString(Tag.ImplementationVersionName, VR.SH, Implementation.versionName()); if (overwriteObject != null) { overwriteObject.copyTo(newDs); } } finally { reader.dispose(); } writer.prepareWriteSequence(writeMeta); for (int i = 0; i < frames; i++) { FileInputStream inputStream = new FileInputStream(src); try { WritableRaster r = (WritableRaster) readRaster(inputStream, i); ColorModel cm = ColorModelFactory.createColorModel(ds); BufferedImage bi = new BufferedImage(cm, r, false, null); IIOImage iioimage = new IIOImage(bi, null, null); writer.writeToSequence(iioimage, null); } catch (NoSuchFieldException ex) { System.err.println(ex.toString()); } catch (IllegalAccessException ex) { System.err.println(ex.toString()); } finally { inputStream.close(); } } writer.endWriteSequence(); } finally { if (output != null) { output.close(); } } }
From source file:org.dcm4che2.tool.dcm2jpg.Dcm2Jpg.java
private void encodeByImageIO(BufferedImage bi, File dest) throws IOException { ImageWriter writer = getImageWriter(imageWriterClassname); ImageOutputStream out = null; try {//from w ww . j av a 2 s . c o m out = ImageIO.createImageOutputStream(dest); writer.setOutput(out); ImageWriteParam iwparam = writer.getDefaultWriteParam(); if (iwparam.canWriteCompressed()) { iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); String[] compressionTypes = iwparam.getCompressionTypes(); if (compressionTypes != null && compressionTypes.length > 0) { if (compressionType != null || iwparam.getCompressionType() == null) { for (int i = 0; i < compressionTypes.length; i++) { if (compressionType == null || compressionTypes[i].compareToIgnoreCase(compressionType) == 0) { iwparam.setCompressionType(compressionTypes[i]); break; } } } } if (imageQuality != null) iwparam.setCompressionQuality(imageQuality); } else if (imageQuality != null) { System.out.println("Selected Image Writer can not compress! imageQuality is ignored!"); } writer.write(null, new IIOImage(bi, null, null), iwparam); } finally { CloseUtils.safeClose(out); writer.dispose(); } }