Example usage for javax.imageio ImageWriter dispose

List of usage examples for javax.imageio ImageWriter dispose

Introduction

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

Prototype

public void dispose() 

Source Link

Document

Allows any resources held by this object to be released.

Usage

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

/**
 * Scale image to fit in the given width.
 * //from  ww w  .  j a va  2 s.  c  om
 * @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./*  ww w  . j a  va 2  s.c o  m*/
 * 
 * @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 a2  s  .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();
}

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 v a 2 s  .  c  om*/
 * <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;
}