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: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 v  a 2  s .  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 w  w.  j  av a2s . co m*/
 * @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  .jav  a  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./*from   w  w  w . j a  v  a  2 s  .com*/
 * 
 * @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:osmb.program.tiledatawriter.TileImageJpegDataWriter.java

@Override
public void processImage(BufferedImage image, OutputStream out) throws IOException {
    if (image.getColorModel().hasAlpha()) {
        // Javas JPEG writes has a bug when the image has alpha transparency
        // see http://stackoverflow.com/questions/4386446/problem-using-imageio-write-jpg-file

        BufferedImage imageRGB = new BufferedImage(image.getWidth(), image.getHeight(),
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g = imageRGB.createGraphics();
        g.drawImage(image, null, 0, 0);// w w  w. j a v a  2 s . c om
        g.dispose();
        image = imageRGB;
    }

    ImageOutputStream imageOut = ImageIO.createImageOutputStream(out);
    jpegImageWriter.setOutput(imageOut);
    IIOImage ioImage = new IIOImage(image, null, null);
    jpegImageWriter.write(null, ioImage, iwp);
}

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

public void processImage(BufferedImage image, OutputStream out) throws IOException {

    if (image.getColorModel().hasAlpha()) {
        // Javas JPEG writes has a bug when the image has alpha transparency
        // see http://stackoverflow.com/questions/4386446/problem-using-imageio-write-jpg-file

        BufferedImage imageRGB = new BufferedImage(image.getWidth(), image.getHeight(),
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g = imageRGB.createGraphics();
        g.drawImage(image, null, 0, 0);/*from   www  .j av a2 s  . c  o  m*/
        g.dispose();
        image = imageRGB;
    }

    ImageOutputStream imageOut = ImageIO.createImageOutputStream(out);
    jpegImageWriter.setOutput(imageOut);
    IIOImage ioImage = new IIOImage(image, null, null);
    jpegImageWriter.write(null, ioImage, iwp);
}

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 . j a  v a2  s  .co 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();
}

From source file:tvbrowserdataservice.file.ProgramField.java

/**
 * This Function loads an image using imageio,
 * resizes it to the Max-Size of Images in TVBrowser and
 * stores it as an compressed jpg./*from  w  w w.  ja va  2 s .c  o m*/
 * <p/>
 * If the Image is smaller than the Max-Size, it isn't altered
 *
 * @param data Image-Data
 * @return resized Image-Data
 */
private static byte[] recreateImage(byte[] data) {
    byte[] newdata = null;
    BufferedImage image = null;
    try {
        // Read Image
        image = ImageIO.read(new ByteArrayInputStream(data));

        int curx = image.getWidth(null);
        int cury = image.getHeight(null);

        // If the Size is < than max, use the original Data to reduce compression
        // artefacts
        if ((curx <= MAX_IMAGE_SIZE_X) && (cury <= MAX_IMAGE_SIZE_Y)) {
            return data;
        }

        int newx = MAX_IMAGE_SIZE_X;
        int newy = (int) ((MAX_IMAGE_SIZE_X / (float) curx) * cury);

        if (newy > MAX_IMAGE_SIZE_Y) {
            newy = MAX_IMAGE_SIZE_Y;
            newx = (int) ((MAX_IMAGE_SIZE_Y / (float) cury) * curx);
        }

        BufferedImage tempPic = new BufferedImage(image.getWidth(null), image.getHeight(null),
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = tempPic.createGraphics();
        g2d.drawImage(image, null, null);
        g2d.dispose();

        BufferedImage newImage = UiUtilities.scaleIconToBufferedImage(tempPic, newx, newy);

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        // Find a jpeg writer
        ImageWriter writer = null;
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg");
        if (iter.hasNext()) {
            writer = iter.next();
        }

        if (writer != null) {
            // Prepare output file
            ImageOutputStream ios = ImageIO.createImageOutputStream(out);
            writer.setOutput(ios);

            JPEGImageWriteParam param = new JPEGImageWriteParam(null);

            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(0.85f);

            // Write the image
            writer.write(null, new IIOImage(newImage, null, null), param);

            // Cleanup
            ios.flush();
            writer.dispose();
            ios.close();

            newdata = out.toByteArray();
        } else {
            mLog.severe("No JPEG-Exporter found. Image is not stored in Data");
        }

    } catch (IOException e) {
        e.printStackTrace();
        newdata = null;
    }

    return newdata;
}