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:org.polymap.core.data.image.ImageEncodeProcessor.java

private void imageioEncodeJPEG(Image image, ChunkedResponseOutputStream out) throws IOException {
    // this code is from http://forums.sun.com/thread.jspa?threadID=5197061
    ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
    ImageWriteParam param = writer.getDefaultWriteParam();
    param.setSourceBands(new int[] { 0, 1, 2 });
    ColorModel cm = new DirectColorModel(24, 0x00ff0000, // Red
            0x0000ff00, // Green
            0x000000ff, // Blue
            0x0); // Alpha
    param.setDestinationType(new ImageTypeSpecifier(cm, cm.createCompatibleSampleModel(1, 1)));

    ImageOutputStream imageOut = ImageIO.createImageOutputStream(out);
    writer.setOutput(imageOut);//from w ww .  j  ava2s. com
    writer.write(null, new IIOImage((RenderedImage) image, null, null), param);
    writer.dispose();
    imageOut.close();
}

From source file:org.sejda.sambox.pdmodel.graphics.image.JPEGFactory.java

private static void encodeImageToJPEGStream(BufferedImage image, float quality, int dpi, OutputStream out)
        throws IOException {
    // encode to JPEG
    ImageOutputStream ios = null;
    ImageWriter imageWriter = null;
    try {/*from ww w .  j  a va2s. co m*/
        // find JAI writer
        imageWriter = ImageIO.getImageWritersBySuffix("jpeg").next();
        ios = ImageIO.createImageOutputStream(out);
        imageWriter.setOutput(ios);

        // add compression
        JPEGImageWriteParam jpegParam = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
        jpegParam.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
        jpegParam.setCompressionQuality(quality);

        // add metadata
        ImageTypeSpecifier imageTypeSpecifier = new ImageTypeSpecifier(image);
        IIOMetadata data = imageWriter.getDefaultImageMetadata(imageTypeSpecifier, jpegParam);
        Element tree = (Element) data.getAsTree("javax_imageio_jpeg_image_1.0");
        Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
        jfif.setAttribute("Xdensity", Integer.toString(dpi));
        jfif.setAttribute("Ydensity", Integer.toString(dpi));
        jfif.setAttribute("resUnits", "1"); // 1 = dots/inch

        // write
        imageWriter.write(data, new IIOImage(image, null, null), jpegParam);
    } finally {
        // clean up
        IOUtils.closeQuietly(out);
        if (ios != null) {
            ios.close();
        }
        if (imageWriter != null) {
            imageWriter.dispose();
        }
    }
}

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

/**
 * Scale image to fit in the given width.
 * /*from  w ww . j  a  va  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);
}

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

/**
 * Scale image to fit in the given width.
 * //from   www .j  ava 2 s.co  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

/**
 * Cache image.//  w  w w . j ava2s  . c om
 * 
 * @param mf
 *          the media file
 * @return the file the cached file
 * @throws Exception
 */
public static Path cacheImage(Path originalFile) throws Exception {
    MediaFile mf = new MediaFile(originalFile);
    Path cachedFile = ImageCache.getCacheDir()
            .resolve(getMD5(originalFile.toString()) + "." + Utils.getExtension(originalFile));
    if (!Files.exists(cachedFile)) {
        // check if the original file exists && size > 0
        if (!Files.exists(originalFile)) {
            throw new FileNotFoundException("unable to cache file: " + originalFile + "; file does not exist");
        }
        if (Files.size(originalFile) == 0) {
            throw new EmptyFileException(originalFile);
        }

        // recreate cache dir if needed
        // rescale & cache
        BufferedImage originalImage = null;
        try {
            originalImage = createImage(originalFile);
        } catch (Exception e) {
            throw new Exception("cannot create image - file seems not to be valid? " + originalFile);
        }

        // calculate width based on MF type
        int desiredWidth = originalImage.getWidth(); // initialize with fallback
        switch (mf.getType()) {
        case FANART:
            if (originalImage.getWidth() > 1000) {
                desiredWidth = 1000;
            }
            break;

        case POSTER:
            if (originalImage.getHeight() > 500) {
                desiredWidth = 350;
            }
            break;

        case EXTRAFANART:
        case THUMB:
        case BANNER:
        case GRAPHIC:
            desiredWidth = 300;
            break;

        default:
            break;
        }

        // special handling for movieset-fanart or movieset-poster
        if (mf.getFilename().startsWith("movieset-fanart") || mf.getFilename().startsWith("movieset-poster")) {
            if (originalImage.getWidth() > 1000) {
                desiredWidth = 1000;
            }
        }

        Point size = calculateSize(desiredWidth, (int) (originalImage.getHeight() / 1.5),
                originalImage.getWidth(), originalImage.getHeight(), true);
        BufferedImage scaledImage = null;

        if (Globals.settings.getImageCacheType() == CacheType.FAST) {
            // scale fast
            scaledImage = Scalr.resize(originalImage, Scalr.Method.BALANCED, Scalr.Mode.FIT_EXACT, size.x,
                    size.y);
        } else {
            // scale with good quality
            scaledImage = Scalr.resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.FIT_EXACT, size.x,
                    size.y);
        }
        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;
        }

        FileImageOutputStream output = new FileImageOutputStream(cachedFile.toFile());
        imgWrtr.setOutput(output);
        IIOImage image = new IIOImage(scaledImage, null, null);
        imgWrtr.write(null, image, imgWrtrPrm);
        imgWrtr.dispose();
        output.flush();
        output.close();
        scaledImage = null;
    }

    if (!Files.exists(cachedFile)) {
        throw new Exception("unable to cache file: " + originalFile);
    }

    return cachedFile;
}

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  ww  w  . j a v  a2s  .  c o m
    }

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