Example usage for javax.imageio IIOImage IIOImage

List of usage examples for javax.imageio IIOImage IIOImage

Introduction

In this page you can find the example usage for javax.imageio IIOImage IIOImage.

Prototype

public IIOImage(Raster raster, List<? extends BufferedImage> thumbnails, IIOMetadata metadata) 

Source Link

Document

Constructs an IIOImage containing a Raster , and thumbnails and metadata associated with it.

Usage

From source file:ScreenCapture.java

private void save() {
    if (ia.getImage() == null) {
        System.out.println("No captured image.");
        return;/*from  www  . j  a va 2s. c om*/
    }
    ImageWriter writer = null;
    ImageOutputStream ios = null;

    try {
        Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");

        if (!iter.hasNext()) {
            System.out.println("Unable to save image to jpeg file type.");
            return;
        }
        writer = (ImageWriter) iter.next();
        ios = ImageIO.createImageOutputStream(new File("c:\\a.jpg"));
        writer.setOutput(ios);
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(0.95f);
        writer.write(null, new IIOImage((BufferedImage) ia.getImage(), null, null), iwp);
    } catch (Exception e2) {
        e2.printStackTrace();
    }

}

From source file:de.jwic.ecolib.controls.chart.ChartControl.java

public void renderImage() throws IOException {
    // create image to draw into
    BufferedImage bi = new BufferedImage(width < 10 ? 10 : width, height < 10 ? 10 : height,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = bi.createGraphics();

    if (chart != null) {
        chart.setBackgroundPaint(Color.WHITE);
        chart.draw(g2d, new Rectangle2D.Double(0, 0, width < 10 ? 10 : width, height < 10 ? 10 : height));
    } else {/*ww w .j a  va  2s  .c o  m*/
        g2d.setColor(Color.BLACK);
        g2d.drawString("No chart has been assigned.", 1, 20);
    }
    // finish drawing
    g2d.dispose();

    // write image data into output stream
    ByteArrayOutputStream out = getImageOutputStream();
    out.reset();
    // create a PNG image
    ImageWriter imageWriter = new PNGImageWriter(null);
    ImageWriteParam param = imageWriter.getDefaultWriteParam();
    imageWriter.setOutput(new MemoryCacheImageOutputStream(out));
    imageWriter.write(null, new IIOImage(bi, null, null), param);
    imageWriter.dispose();

    setMimeType(MIME_TYPE_PNG);
}

From source file:mobac.program.tiledatawriter.TileImageJpegDataWriter.java

public void processImage(BufferedImage image, OutputStream out) throws IOException {
    ImageOutputStream imageOut = ImageIO.createImageOutputStream(out);
    jpegImageWriter.setOutput(imageOut);
    IIOImage ioImage = new IIOImage(image, null, null);
    jpegImageWriter.write(null, ioImage, iwp);
}

From source file:ar.com.zauber.common.image.impl.AbstractImage.java

/**
 * Creates a thumbnail/*from  www .j  ava 2 s.  c  o  m*/
 * 
 * @param is data source
 * @param os data source
 * @throws IOException if there is a problem reading is
 */
public static void createThumbnail(final InputStream is, final OutputStream os, final int target)
        throws IOException {
    final float compression = 0.85F;
    ImageWriter writer = null;
    MemoryCacheImageOutputStream mos = null;
    Graphics2D graphics2D = null;
    try {
        final BufferedImage bi = ImageIO.read(is);
        final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("JPG");
        if (!iter.hasNext()) {
            throw new IllegalStateException("can't find JPG subsystem");
        }

        int w = bi.getWidth(), h = bi.getHeight();
        if (w < target && h < target) {
            // nothing to recalculate, ya es chiquita.
        } else {
            if (w > h) {
                h = target * bi.getHeight() / bi.getWidth();
                w = target;
            } else {
                w = target * bi.getWidth() / bi.getHeight();
                h = target;
            }
        }
        // draw original image to thumbnail image object and
        // scale it to the new size on-the-fly
        final BufferedImage thumbImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(bi, 0, 0, w, h, null);

        writer = (ImageWriter) iter.next();
        final ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(compression);
        mos = new MemoryCacheImageOutputStream(os);
        writer.setOutput(mos);
        writer.write(null, new IIOImage(thumbImage, null, null), iwp);
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (mos != null) {
            mos.close();
        }
        if (graphics2D != null) {
            graphics2D.dispose();
        }
        is.close();
        os.close();
    }
}

From source file:org.shredzone.cilla.service.resource.ImageProcessorImpl.java

/**
 * Writes a JPEG file with adjustable compression quality.
 *
 * @param image/*from   w  ww .  j a v  a  2 s  .  c  o  m*/
 *            {@link BufferedImage} to write
 * @param out
 *            {@link ImageOutputStream} to write to
 * @param quality
 *            Compression quality between 0.0f (worst) and 1.0f (best)
 */
private void jpegQualityWriter(BufferedImage image, ImageOutputStream out, float quality) throws IOException {
    ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();

    ImageWriteParam iwp = writer.getDefaultWriteParam();
    iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwp.setCompressionQuality(quality);

    IIOImage ioImage = new IIOImage(image, null, null);

    writer.setOutput(out);
    writer.write(null, ioImage, iwp);
    writer.dispose();
}

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   w  w w .  j  ava 2 s .  c o m
    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.lingxiang2014.util.ImageUtils.java

public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
    Assert.notNull(srcFile);//from  ww  w.j a v  a  2  s .  c o  m
    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:compressor.Compressor.java

void compress_images(String src, String dest) throws IOException {

    File f = null;/*w  w w . j a  v  a 2  s.  c  om*/
    String[] paths;

    try {
        // create new file
        f = new File(src);

        // array of files and directory
        paths = f.list();

        File file = new File(dest + "compressed");
        if (!file.exists()) {
            if (file.mkdir()) {
                System.out.println("Directory is created!");
            } else {
                System.out.println("Failed to create directory!");
            }
        }
        dest = dest + "compressed/";

        // for each name in the path array
        for (String path : paths) {
            // prints filename and directory name

            File input = new File(src + path);
            BufferedImage image = ImageIO.read(input);

            File compressedImageFile = new File(dest + path);
            OutputStream os = new FileOutputStream(compressedImageFile);

            Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
            ImageWriter writer = (ImageWriter) writers.next();

            ImageOutputStream ios = ImageIO.createImageOutputStream(os);
            writer.setOutput(ios);

            ImageWriteParam param = writer.getDefaultWriteParam();

            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(0.05f);
            writer.write(null, new IIOImage(image, null, null), param);

            os.close();
            ios.close();
            writer.dispose();

        }
    } catch (Exception e) {
    }

}

From source file:ImageUtils.java

/**
 * Compress and save an image to the disk. Currently this method only supports JPEG images.
 * /*from ww  w .  j a v  a 2 s  . c  o  m*/
 * @param image The image to save
 * @param toFileName The filename to use
 * @param type The image type. Use <code>ImageUtils.IMAGE_JPEG</code> to save as JPEG images,
 * or <code>ImageUtils.IMAGE_PNG</code> to save as PNG.
 */
public static void saveCompressedImage(BufferedImage image, String toFileName, int type) {
    try {
        if (type == IMAGE_PNG) {
            throw new UnsupportedOperationException("PNG compression not implemented");
        }

        Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
        ImageWriter writer;
        writer = (ImageWriter) iter.next();

        ImageOutputStream ios = ImageIO.createImageOutputStream(new File(toFileName));
        writer.setOutput(ios);

        ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());

        iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwparam.setCompressionQuality(0.7F);

        writer.write(null, new IIOImage(image, null, null), iwparam);

        ios.flush();
        writer.dispose();
        ios.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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  ww.  j  a va 2s. 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);
    }
}