Example usage for javax.imageio ImageWriter getDefaultWriteParam

List of usage examples for javax.imageio ImageWriter getDefaultWriteParam

Introduction

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

Prototype

public ImageWriteParam getDefaultWriteParam() 

Source Link

Document

Returns a new ImageWriteParam object of the appropriate type for this file format containing default values, that is, those values that would be used if no ImageWriteParam object were specified.

Usage

From source file:de.bamamoto.mactools.png2icns.Scaler.java

public static void save(BufferedImage image, String filename) throws IOException {
    Iterator writers = ImageIO.getImageWritersByFormatName("PNG");
    if (writers.hasNext()) {
        ImageWriter imageWriter = (ImageWriter) writers.next();
        ImageWriteParam params = imageWriter.getDefaultWriteParam();

        File outFile = new File(filename);
        try (FileImageOutputStream output = new FileImageOutputStream(outFile)) {
            imageWriter.setOutput(output);
            IIOImage outImage = new IIOImage(image, null, null);
            imageWriter.write(null, outImage, params);
        }//from  w ww  .j  a v a2s . com
    }
}

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   ww w  . j ava2s.co  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:ch.rasc.downloadchart.DownloadChartServlet.java

private static void handleJpg(HttpServletResponse response, byte[] imageData, Integer width, Integer height,
        String filename, JpegOptions options) throws IOException {

    response.setContentType("image/jpeg");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".jpg\";");

    BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageData));

    Dimension newDimension = calculateDimension(image, width, height);
    int imgWidth = image.getWidth();
    int imgHeight = image.getHeight();
    if (newDimension != null) {
        imgWidth = newDimension.width;/*w  ww.ja  v a2  s.  co m*/
        imgHeight = newDimension.height;
    }

    BufferedImage newImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = newImage.createGraphics();
    g.drawImage(image, 0, 0, imgWidth, imgHeight, Color.BLACK, null);
    g.dispose();

    if (newDimension != null) {
        g.setComposite(AlphaComposite.Src);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    }

    try (ImageOutputStream ios = ImageIO.createImageOutputStream(response.getOutputStream())) {
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg");
        ImageWriter writer = iter.next();
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        if (options != null && options.quality != null && options.quality != 0 && options.quality != 100) {
            iwp.setCompressionQuality(options.quality / 100f);
        } else {
            iwp.setCompressionQuality(1);
        }
        writer.setOutput(ios);
        writer.write(null, new IIOImage(newImage, null, null), iwp);
        writer.dispose();
    }
}

From source file:com.db.comserv.main.utilities.HttpCaller.java

public static String compress(String imageString, float quality) throws IOException {
    byte[] imageByte = Base64.decodeBase64(imageString);
    ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
    BufferedImage image = ImageIO.read(bis);
    bis.close();/*from   w ww .j  ava 2  s. co m*/

    // Get a ImageWriter for given extension format.

    Iterator<ImageWriter> writers = ImageIO.getImageWritersBySuffix("jpg");
    if (!writers.hasNext())
        throw new IllegalStateException("No writers found");

    ImageWriter writer = (ImageWriter) writers.next();
    // Create the ImageWriteParam to compress the image.
    ImageWriteParam param = writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionQuality(quality);

    // The output will be a ByteArrayOutputStream (in memory)
    ByteArrayOutputStream bos = new ByteArrayOutputStream(32768);
    ImageOutputStream ios = ImageIO.createImageOutputStream(bos);
    writer.setOutput(ios);
    writer.write(null, new IIOImage(image, null, null), param);
    ios.flush(); // otherwise the buffer size will be zero!
    byte[] encodedBytes = Base64.encodeBase64(bos.toByteArray());

    return new String(encodedBytes);
}

From source file:com.mirth.connect.server.util.DICOMUtil.java

private static byte[] saveAsJpeg(ImagePlus imagePlug, int quality) {
    int imageType = BufferedImage.TYPE_INT_RGB;

    if (imagePlug.getProcessor().isDefaultLut()) {
        imageType = BufferedImage.TYPE_BYTE_GRAY;
    }/*from  ww w. j  ava 2  s.  co  m*/

    BufferedImage bufferedImage = new BufferedImage(imagePlug.getWidth(), imagePlug.getHeight(), imageType);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        Graphics graphics = bufferedImage.createGraphics();
        graphics.drawImage(imagePlug.getImage(), 0, 0, null);
        graphics.dispose();
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
        writer.setOutput(ImageIO.createImageOutputStream(baos));
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality / 100f);

        if (quality == 100) {
            param.setSourceSubsampling(1, 1, 0, 0);
        }

        IIOImage iioImage = new IIOImage(bufferedImage, null, null);
        writer.write(null, iioImage, param);
        return baos.toByteArray();
    } catch (Exception e) {
        logger.error("Error converting dcm file", e);
    } finally {
        IOUtils.closeQuietly(baos);
    }

    return null;
}

From source file:com.mirth.connect.server.util.DICOMMessageUtil.java

private static byte[] saveAsJpeg(ImagePlus imagePlug, int quality) {
    int imageType = BufferedImage.TYPE_INT_RGB;

    if (imagePlug.getProcessor().isDefaultLut()) {
        imageType = BufferedImage.TYPE_BYTE_GRAY;
    }//from   w w w. j a  va 2s.com

    BufferedImage bufferedImage = new BufferedImage(imagePlug.getWidth(), imagePlug.getHeight(), imageType);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        Graphics graphics = bufferedImage.createGraphics();
        graphics.drawImage(imagePlug.getImage(), 0, 0, null);
        graphics.dispose();
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
        writer.setOutput(ImageIO.createImageOutputStream(baos));
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality / 100f);

        if (quality == 100) {
            param.setSourceSubsampling(1, 1, 0, 0);
        }

        IIOImage iioImage = new IIOImage(bufferedImage, null, null);
        writer.write(null, iioImage, param);
        return baos.toByteArray();
    } catch (Exception e) {
        logger.error("Error Converting DICOM image", e);
    } finally {
        IOUtils.closeQuietly(baos);
    }

    return null;
}

From source file:editeurpanovisu.ReadWriteImage.java

/**
 *
 * @param img/*  w  ww .  j  av a  2  s  . co  m*/
 * @param destFile
 * @param sharpen
 * @param sharpenLevel
 * @throws IOException
 */
public static void writePng(Image img, String destFile, boolean sharpen, float sharpenLevel)
        throws IOException {
    sharpenMatrix = calculeSharpenMatrix(sharpenLevel);
    BufferedImage imageRGBSharpen = null;
    IIOImage iioImage = null;
    BufferedImage image = SwingFXUtils.fromFXImage(img, null); // Get buffered image.
    BufferedImage imageRGB = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.BITMASK);
    Graphics2D graphics = imageRGB.createGraphics();
    graphics.drawImage(image, 0, 0, null);
    if (sharpen) {
        imageRGBSharpen = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
        Kernel kernel = new Kernel(3, 3, sharpenMatrix);
        ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        cop.filter(imageRGB, imageRGBSharpen);
    }
    ImageWriter writer = null;
    FileImageOutputStream output = null;
    try {
        writer = ImageIO.getImageWritersByFormatName("png").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        output = new FileImageOutputStream(new File(destFile));
        writer.setOutput(output);
        if (sharpen) {
            iioImage = new IIOImage(imageRGBSharpen, null, null);
        } else {
            iioImage = new IIOImage(imageRGB, null, null);
        }
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (output != null) {
            output.close();
        }
    }
    graphics.dispose();
}

From source file:editeurpanovisu.ReadWriteImage.java

/**
 *
 * @param img//from w  ww  . j  a v  a2 s .c  o  m
 * @param destFile
 * @param sharpen
 * @param sharpenLevel
 * @throws IOException
 */
public static void writeBMP(Image img, String destFile, boolean sharpen, float sharpenLevel)
        throws IOException {
    sharpenMatrix = calculeSharpenMatrix(sharpenLevel);
    BufferedImage imageRGBSharpen = null;
    IIOImage iioImage = null;

    BufferedImage image = SwingFXUtils.fromFXImage(img, null); // Get buffered image.
    BufferedImage imageRGB = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.OPAQUE); // Remove alpha-channel from buffered image.

    Graphics2D graphics = imageRGB.createGraphics();
    graphics.drawImage(image, 0, 0, null);
    if (sharpen) {

        imageRGBSharpen = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
        Kernel kernel = new Kernel(3, 3, sharpenMatrix);
        ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        cop.filter(imageRGB, imageRGBSharpen);
    }
    ImageWriter writer = null;
    FileImageOutputStream output = null;
    try {
        writer = ImageIO.getImageWritersByFormatName("bmp").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        output = new FileImageOutputStream(new File(destFile));
        writer.setOutput(output);
        if (sharpen) {
            iioImage = new IIOImage(imageRGBSharpen, null, null);
        } else {
            iioImage = new IIOImage(imageRGB, null, null);
        }
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (output != null) {
            output.close();
        }
    }
    graphics.dispose();
}

From source file:editeurpanovisu.ReadWriteImage.java

/**
 *
 * @param img/*from w w  w  .  j av a  2s  . c o  m*/
 * @param destFile
 * @param quality
 * @param sharpen
 * @param sharpenLevel
 * @throws IOException
 */
public static void writeJpeg(Image img, String destFile, float quality, boolean sharpen, float sharpenLevel)
        throws IOException {
    sharpenMatrix = calculeSharpenMatrix(sharpenLevel);
    BufferedImage imageRGBSharpen = null;
    IIOImage iioImage = null;
    BufferedImage image = SwingFXUtils.fromFXImage(img, null); // Get buffered image.

    BufferedImage imageRGB = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.OPAQUE); // Remove alpha-channel from buffered image.

    Graphics2D graphics = imageRGB.createGraphics();
    graphics.drawImage(image, 0, 0, null);
    if (sharpen) {
        imageRGBSharpen = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
        Kernel kernel = new Kernel(3, 3, sharpenMatrix);
        ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        cop.filter(imageRGB, imageRGBSharpen);
    }
    ImageWriter writer = null;
    FileImageOutputStream output = null;
    try {
        writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality);
        output = new FileImageOutputStream(new File(destFile));
        writer.setOutput(output);
        if (sharpen) {
            iioImage = new IIOImage(imageRGBSharpen, null, null);
        } else {
            iioImage = new IIOImage(imageRGB, null, null);
        }
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (output != null) {
            output.close();
        }
    }
    graphics.dispose();
}

From source file:net.intelliant.util.UtilCommon.java

private static String generateCompressedImageForInputFile(String locationInFileSystem, String srcFileName)
        throws NoSuchAlgorithmException, IOException {
    String outputFileName = srcFileName;
    File srcFile = new File(locationInFileSystem, srcFileName);
    File compressedFile = null;/*from ww  w.  j a va 2 s.  c om*/
    FileImageOutputStream outputStream = null;
    try {
        if (srcFile.exists()) {
            String md5sum = getMD5SumForFile(srcFile.getAbsolutePath());
            int extentionIndex = srcFileName.lastIndexOf("."); // find index of extension.
            if (extentionIndex != -1) {
                outputFileName = outputFileName.replaceFirst("\\.", "_" + md5sum + ".");
            }
            compressedFile = new File(locationInFileSystem, outputFileName);
            if (Debug.infoOn()) {
                Debug.logInfo("[generateCompressedImageFor] sourceFile >> " + srcFile.getAbsolutePath(),
                        module);
                Debug.logInfo("[generateCompressedImageFor] md5sum >> " + md5sum, module);
                Debug.logInfo(
                        "[generateCompressedImageFor] compressedFile >> " + compressedFile.getAbsolutePath(),
                        module);
            }
            if (!compressedFile.exists()) {
                if (Debug.infoOn()) {
                    Debug.logInfo("[generateCompressedImageFor] compressed file does NOT exist..", module);
                }
                Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
                ImageWriter imageWriter = (ImageWriter) iter.next();
                ImageWriteParam iwp = imageWriter.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality(Float.parseFloat(imageCompressionQuality)); // an integer between 0 and 1, 1 specifies minimum compression and maximum quality
                BufferedImage bufferedImage = ImageIO.read(srcFile);
                outputStream = new FileImageOutputStream(compressedFile);
                imageWriter.setOutput(outputStream);
                IIOImage image = new IIOImage(bufferedImage, null, null);
                imageWriter.write(null, image, iwp);
            } else {
                if (Debug.infoOn()) {
                    Debug.logInfo(
                            "[generateCompressedImageFor] compressed file exists, not compressing again..",
                            module);
                }
            }
        } else {
            Debug.logWarning(String.format("Source image file does NOT exist..", srcFile), module);
        }
    } finally {
        if (outputStream != null) {
            outputStream.close();
            outputStream = null;
        }
    }
    return outputFileName;
}