Example usage for javax.imageio ImageWriter write

List of usage examples for javax.imageio ImageWriter write

Introduction

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

Prototype

public abstract void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param)
        throws IOException;

Source Link

Document

Appends a complete image stream containing a single image and associated stream and image metadata and thumbnails to the output.

Usage

From source file:org.freecine.filmscan.Project.java

private void saveImage(RenderedImage img, File file) {
    // Find a writer for that file extensions
    // Try to determine the file type based on extension
    String ftype = "jpg";
    String imageFname = file.getName();
    int extIndex = imageFname.lastIndexOf(".") + 1;
    if (extIndex > 0) {
        ftype = imageFname.substring(extIndex);
    }//from w  w w.  ja va2s .co m

    ImageWriter writer = null;
    Iterator iter = ImageIO.getImageWritersBySuffix(ftype);
    writer = (ImageWriter) iter.next();

    if (writer != null) {
        ImageOutputStream ios = null;
        try {
            // Prepare output file
            ios = ImageIO.createImageOutputStream(file);
            writer.setOutput(ios);
            // Set some parameters
            ImageWriteParam param = writer.getDefaultWriteParam();
            writer.write(null, new IIOImage(img, null, null), param);

            // Cleanup
            ios.flush();

        } catch (IOException ex) {
            log.severe("Error saving image " + file.getAbsolutePath() + ": " + ex.getMessage());
        } finally {
            if (ios != null) {
                try {
                    ios.close();
                } catch (IOException e) {
                    log.severe("Error closing output stream: " + e.getMessage());
                }
            }
            writer.dispose();
        }
    }
}

From source file:ScreenCapture.java

private void save() {
    if (ia.getImage() == null) {
        System.out.println("No captured image.");
        return;//from  w  w w . j a  va  2  s . 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:ar.com.zauber.common.image.impl.AbstractImage.java

/**
 * Creates a thumbnail//from w w  w .  j a  v a2s .  co 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:pl.edu.icm.visnow.lib.utils.ImageUtilities.java

public static void writeJpeg(BufferedImage img, float quality, File file) throws IOException {
    if (img == null) {
        return;//from w  w w . ja  v  a 2s .  c  om
    }

    float q = quality;
    if (q < 0) {
        q = 0;
    }
    if (q > 1) {
        q = 1;
    }

    Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
    ImageWriter writer = (ImageWriter) iter.next();
    ImageWriteParam iwp = writer.getDefaultWriteParam();
    iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwp.setCompressionQuality(q); // float between 0 and 1
                                  // 1 specifies minimum compression and maximum quality

    FileImageOutputStream output = new FileImageOutputStream(file);
    writer.setOutput(output);
    IIOImage image = new IIOImage(img, null, null);
    writer.write(null, image, iwp);
    writer.dispose();
}

From source file:com.sire.web.CajFacturaEnviadaBean.java

private void savePicture() {
    if (file != null) {
        try {//from w ww .jav  a  2 s . c  o  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.itextpdf.text.pdf.pdfcleanup.PdfCleanUpRenderListener.java

private byte[] getJPGBytes(BufferedImage image) {
    ByteArrayOutputStream outputStream = null;

    try {//from  ww  w  .  j a v  a 2  s . c  om
        ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
        ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();
        jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        jpgWriteParam.setCompressionQuality(1.0f);

        outputStream = new ByteArrayOutputStream();
        jpgWriter.setOutput(new MemoryCacheImageOutputStream((outputStream)));
        IIOImage outputImage = new IIOImage(image, null, null);

        jpgWriter.write(null, outputImage, jpgWriteParam);
        jpgWriter.dispose();
        outputStream.flush();

        return outputStream.toByteArray();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        closeOutputStream(outputStream);
    }
}

From source file:org.nekorp.workflow.desktop.servicio.reporte.orden.servicio.OrdenServicioDataFactory.java

private void saveJPG(BufferedImage img, File file) {
    ImageWriter writer = null;
    FileImageOutputStream output = null;
    try {//from  w w  w  . j  a  v a2  s.  c o m
        writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(1);
        output = new FileImageOutputStream(file);
        writer.setOutput(output);
        IIOImage iioImage = new IIOImage(img, null, null);
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        try {
            if (writer != null) {
                writer.dispose();
            }
            if (output != null) {
                output.close();
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}

From source file:com.lingxiang2014.util.ImageUtils.java

public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
    Assert.notNull(srcFile);/*w  w  w  .  j  a v  a 2  s.  co 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:org.tinymediamanager.core.ImageCache.java

/**
 * Scale image to fit in the given width.
 * //from   ww w  .ja  v a 2  s . c  o  m
 * @param file
 *          the original image file
 * @param width
 *          the width
 * @return the input stream
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 * @throws InterruptedException
 */
public static InputStream scaleImage(Path file, int width) throws IOException, InterruptedException {
    BufferedImage originalImage = null;
    try {
        originalImage = createImage(file);
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }

    Point size = new Point();
    size.x = width;
    size.y = size.x * originalImage.getHeight() / originalImage.getWidth();

    // BufferedImage scaledImage = Scaling.scale(originalImage, size.x, size.y);
    BufferedImage scaledImage = Scalr.resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.AUTOMATIC, size.x,
            size.y, Scalr.OP_ANTIALIAS);
    originalImage = null;

    ImageWriter imgWrtr = null;
    ImageWriteParam imgWrtrPrm = null;

    // here we have two different ways to create our thumb
    // a) a scaled down jpg/png (without transparency) which we have to modify since OpenJDK cannot call native jpg encoders
    // b) a scaled down png (with transparency) which we can store without any more modifying as png
    if (hasTransparentPixels(scaledImage)) {
        // transparent image -> png
        imgWrtr = ImageIO.getImageWritersByFormatName("png").next();
        imgWrtrPrm = imgWrtr.getDefaultWriteParam();

    } else {
        // non transparent image -> jpg
        // convert to rgb
        BufferedImage rgb = new BufferedImage(scaledImage.getWidth(), scaledImage.getHeight(),
                BufferedImage.TYPE_INT_RGB);
        ColorConvertOp xformOp = new ColorConvertOp(null);
        xformOp.filter(scaledImage, rgb);
        imgWrtr = ImageIO.getImageWritersByFormatName("jpg").next();
        imgWrtrPrm = imgWrtr.getDefaultWriteParam();
        imgWrtrPrm.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
        imgWrtrPrm.setCompressionQuality(0.80f);

        scaledImage = rgb;
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageOutputStream output = ImageIO.createImageOutputStream(baos);
    imgWrtr.setOutput(output);
    IIOImage outputImage = new IIOImage(scaledImage, null, null);
    imgWrtr.write(null, outputImage, imgWrtrPrm);
    imgWrtr.dispose();
    scaledImage = null;

    byte[] bytes = baos.toByteArray();

    output.flush();
    output.close();
    baos.close();

    return new ByteArrayInputStream(bytes);
}

From source file:org.tinymediamanager.core.ImageCache.java

/**
 * Scale image to fit in the given width.
 * /* www .  java  2 s. c  om*/
 * @param imageUrl
 *          the image url
 * @param width
 *          the width
 * @return the input stream
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 * @throws InterruptedException
 */
public static InputStream scaleImage(String imageUrl, int width) throws IOException, InterruptedException {
    Url url = new Url(imageUrl);

    BufferedImage originalImage = null;
    try {
        originalImage = createImage(url.getBytes());
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }

    Point size = new Point();
    size.x = width;
    size.y = size.x * originalImage.getHeight() / originalImage.getWidth();

    // BufferedImage scaledImage = Scaling.scale(originalImage, size.x, size.y);
    BufferedImage scaledImage = Scalr.resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.AUTOMATIC, size.x,
            size.y, Scalr.OP_ANTIALIAS);
    originalImage = null;

    ImageWriter imgWrtr = null;
    ImageWriteParam imgWrtrPrm = null;

    // here we have two different ways to create our thumb
    // a) a scaled down jpg/png (without transparency) which we have to modify since OpenJDK cannot call native jpg encoders
    // b) a scaled down png (with transparency) which we can store without any more modifying as png
    if (hasTransparentPixels(scaledImage)) {
        // transparent image -> png
        imgWrtr = ImageIO.getImageWritersByFormatName("png").next();
        imgWrtrPrm = imgWrtr.getDefaultWriteParam();

    } else {
        // non transparent image -> jpg
        // convert to rgb
        BufferedImage rgb = new BufferedImage(scaledImage.getWidth(), scaledImage.getHeight(),
                BufferedImage.TYPE_INT_RGB);
        ColorConvertOp xformOp = new ColorConvertOp(null);
        xformOp.filter(scaledImage, rgb);
        imgWrtr = ImageIO.getImageWritersByFormatName("jpg").next();
        imgWrtrPrm = imgWrtr.getDefaultWriteParam();
        imgWrtrPrm.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
        imgWrtrPrm.setCompressionQuality(0.80f);

        scaledImage = rgb;
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageOutputStream output = ImageIO.createImageOutputStream(baos);
    imgWrtr.setOutput(output);
    IIOImage outputImage = new IIOImage(scaledImage, null, null);
    imgWrtr.write(null, outputImage, imgWrtrPrm);
    imgWrtr.dispose();
    scaledImage = null;

    byte[] bytes = baos.toByteArray();

    output.flush();
    output.close();
    baos.close();

    return new ByteArrayInputStream(bytes);
}