Example usage for javax.imageio ImageWriteParam setCompressionQuality

List of usage examples for javax.imageio ImageWriteParam setCompressionQuality

Introduction

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

Prototype

public void setCompressionQuality(float quality) 

Source Link

Document

Sets the compression quality to a value between 0 and 1 .

Usage

From source file:compressor.Compressor.java

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

    File f = null;//from w w  w .j av  a2  s.c  o m
    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:ScreenCapture.java

private void save() {
    if (ia.getImage() == null) {
        System.out.println("No captured image.");
        return;//  w w w  .  j av  a2 s  .  c  o  m
    }
    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:doge.photo.DogePhotoManipulator.java

@Override
public Photo manipulate(Photo photo) throws IOException {
    BufferedImage sourceImage = readImage(photo);
    BufferedImage destinationImage = manipulate(sourceImage);
    Photo resultPhoto = () -> {/*from w w w. ja  va 2 s. co  m*/
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(0.85f);
        writer.setOutput(ios);
        writer.write(null, new IIOImage(destinationImage, null, null), param);
        ImageIO.write(destinationImage, "jpeg", outputStream);
        return new ByteArrayInputStream(outputStream.toByteArray());
    };
    return resultPhoto;
}

From source file:de.inren.service.picture.PictureModificationServiceImpl.java

private void writeJpeg(BufferedImage image, File file, float quality) throws IOException {
    ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
    ImageWriteParam iwp = writer.getDefaultWriteParam();
    iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwp.setCompressionQuality(quality);

    FileImageOutputStream output = new FileImageOutputStream(file);
    writer.setOutput(output);/*from www. jav a2s . c  o m*/
    writer.write(null, new IIOImage(image, null, null), iwp);
}

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

private void savePicture() {
    if (file != null) {
        try {/*  w ww .  j a va  2  s  .com*/
            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:org.yamj.core.service.file.FileStorageService.java

public void storeImage(String filename, StorageType type, BufferedImage bi, ImageFormat imageFormat,
        int quality) throws Exception {
    LOG.debug("Store {} {} image: {}", type, imageFormat, filename);
    String storageFileName = getStorageName(type, filename);
    File outputFile = new File(storageFileName);

    ImageWriter writer = null;//from ww  w. j  a  v  a  2  s.  c  o m
    FileImageOutputStream output = null;
    try {
        if (ImageFormat.PNG == imageFormat) {
            ImageIO.write(bi, "png", outputFile);
        } else {
            float jpegQuality = (float) quality / 100;
            BufferedImage bufImage = new BufferedImage(bi.getWidth(), bi.getHeight(),
                    BufferedImage.TYPE_INT_RGB);
            bufImage.createGraphics().drawImage(bi, 0, 0, null, null);

            @SuppressWarnings("rawtypes")
            Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
            writer = (ImageWriter) iter.next();

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

            output = new FileImageOutputStream(outputFile);
            writer.setOutput(output);
            IIOImage image = new IIOImage(bufImage, null, null);
            writer.write(null, image, iwp);
        }
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (output != null) {
            try {
                output.close();
            } catch (IOException ex) {
                LOG.trace("Failed to close stream: {}", ex.getMessage(), ex);
            }
        }
    }
}

From source file:com.itextpdf.text.pdf.pdfcleanup.PdfCleanUpRenderListener.java

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

    try {/*ww  w .  j a  va  2s  . c o  m*/
        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;//from  w  ww .j  a  v a 2  s .  c  om
    FileImageOutputStream output = null;
    try {
        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:edu.ku.brc.specify.utilapps.ERDVisualizer.java

public void writeJPEG(File outfile, BufferedImage bufferedImage, float compressionQuality) {
    try {/*from   w  w  w .ja v a 2 s  .  c  om*/

        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();
    }

}