Example usage for javax.imageio ImageReader read

List of usage examples for javax.imageio ImageReader read

Introduction

In this page you can find the example usage for javax.imageio ImageReader read.

Prototype

public BufferedImage read(int imageIndex) throws IOException 

Source Link

Document

Reads the image indexed by imageIndex and returns it as a complete BufferedImage , using a default ImageReadParam .

Usage

From source file:nl.b3p.imagetool.ImageTool.java

/**
 * Reads an image from an http input stream.
 *
 * @param method Apache HttpClient GetMethod object
 * @param mime String representing the mime type of the image.
 *
 * @return BufferedImage//from w w w  .  j  av  a 2  s. c  o  m
 *
 * @throws Exception
 */
// <editor-fold defaultstate="" desc="readImage(GetMethod method, String mime) method.">
public static BufferedImage readImage(InputStream is, String mime) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int bytesRead = 0;
    byte[] buffer = new byte[2048];
    while (bytesRead != -1) {
        bytesRead = is.read(buffer, 0, buffer.length);
        if (bytesRead > 0) {
            baos.write(buffer, 0, bytesRead);
        }
    }
    ImageReader ir = null;
    BufferedImage i = null;
    try {
        if (mime.indexOf(";") != -1) {
            mime = mime.substring(0, mime.indexOf(";"));
        }
        String mimeType = getMimeType(mime);

        /* TODO: Kijken waarom er geen mime type meer binnenkomt. Wellicht door de
         * HttpClient vernieuwing in kaartenbalie ? */
        if (mimeType == null) {
            mimeType = "image/png";
        }

        if (mimeType == null) {
            log.error("Response from server not understood (mime = " + mime + "): " + baos.toString());
            throw new Exception(
                    "Response from server not understood (mime = " + mime + "): " + baos.toString());
        }

        ir = getReader(mimeType);
        if (ir == null) {
            log.error("no reader available for imageformat: "
                    + mimeType.substring(mimeType.lastIndexOf("/") + 1));
            throw new Exception("no reader available for imageformat: "
                    + mimeType.substring(mimeType.lastIndexOf("/") + 1));
        }
        //TODO Make smarter.. Possibly faster... But keep reporting!
        ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(baos.toByteArray()));
        ir.setInput(stream, true);
        i = ir.read(0);
        //if image is a png, has no alpha and has a tRNS then make that color transparent.
        if (!i.getColorModel().hasAlpha() && ir.getImageMetadata(0) instanceof PNGMetadata) {
            PNGMetadata metadata = (PNGMetadata) ir.getImageMetadata(0);
            if (metadata.tRNS_present) {
                int alphaPix = (metadata.tRNS_red << 16) | (metadata.tRNS_green << 8) | (metadata.tRNS_blue);
                BufferedImage tmp = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_INT_ARGB);
                for (int x = 0; x < i.getWidth(); x++) {
                    for (int y = 0; y < i.getHeight(); y++) {
                        int rgb = i.getRGB(x, y);
                        rgb = (rgb & 0xFFFFFF) == alphaPix ? alphaPix : rgb;
                        tmp.setRGB(x, y, rgb);
                    }
                }
                i = tmp;
            }
        }
    } finally {
        if (ir != null) {
            ir.dispose();
        }
    }
    return i;
}

From source file:org.medici.bia.controller.manuscriptviewer.IIPImageServerController.java

/**
 * This method retun a specific tiled image.
 * /*ww  w.j  av a 2 s .co  m*/
 * @param httpServletRequest
 * @param httpServletResponse
 */
private void generateFullImage(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
    File imageFile = new File(ApplicationPropertyManager.getApplicationProperty("iipimage.image.path")
            + httpServletRequest.getParameter("FIF"));

    ImageInputStream imageInputStream = null;
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    InputStream inputStream = null;

    try {
        if (imageFile.canRead()) {
            // Reading complete tiff information
            imageInputStream = ImageIO.createImageInputStream(imageFile);
        } else {
            logger.error("File " + imageFile.toString() + " is not present on filesystem. ");
            imageFile = new File(ApplicationPropertyManager.getApplicationProperty("iipimage.image.path")
                    + ApplicationPropertyManager.getApplicationProperty("iipimage.image.notavailable"));
            if (imageFile.canRead()) {
                // Reading complete tiff information
                imageInputStream = ImageIO.createImageInputStream(imageFile);
            } else {
                logger.error("File " + imageFile.toString() + " is not present on filesystem. ");
            }
        }

        if (imageInputStream != null) {
            Iterator<ImageReader> readers = ImageIO.getImageReaders(imageInputStream);
            ImageReader reader = readers.next();
            reader.setInput(imageInputStream, true, true);

            // Reading image position requested
            Integer imageFullIndex = NumberUtils.createInteger(httpServletRequest.getParameter("full"));
            // Positioning at correct page
            BufferedImage pageImage = reader.read(imageFullIndex);
            // preparing image for output
            ImageIO.write(pageImage, "jpeg", byteArrayOutputStream);
            inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            // writing image to output
            httpServletResponse.setContentType("image/jpeg");
            IOUtils.copy(inputStream, httpServletResponse.getOutputStream());
        }
        // Flushing request
        httpServletResponse.getOutputStream().flush();
    } catch (IOException ioException) {
        logger.debug(ioException);
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException ioException) {
        }
        try {
            if (byteArrayOutputStream != null) {
                byteArrayOutputStream.close();
            }
        } catch (IOException ioException) {
        }
        try {
            if (imageInputStream != null) {
                imageInputStream.close();
            }
        } catch (IOException ioException) {
        }
    }
}

From source file:org.paxle.gui.impl.servlets.ConfigView.java

public void writeImage(HttpServletRequest request, HttpServletResponse response, Context context)
        throws Exception {
    final String pid = request.getParameter("pid");
    if (pid == null) {
        response.sendError(501, "No pid supplied.");
        return;//from ww  w.  ja  va  2s  .c  o m
    }

    final String bundleID = request.getParameter("bundleID");
    if (bundleID == null) {
        response.sendError(501, "No bundle-ID supplied.");
        return;
    }

    final ConfigTool configTool = (ConfigTool) context.get(ConfigTool.TOOL_NAME);
    if (configTool == null) {
        response.sendError(501, "Config-Tool not found.");
        return;
    }

    final Configurable configurabel = configTool.getConfigurable(Integer.valueOf(bundleID), pid);
    if (configurabel == null) {
        response.sendError(501, String
                .format("No configurable component found for bundle-ID '%s' and PID '%s'.", bundleID, pid));
        return;
    }

    // loading metadata
    final ObjectClassDefinition ocd = configurabel.getObjectClassDefinition();
    if (ocd == null) {
        response.sendError(501,
                String.format("No ObjectClassDefinition found for service with PID '%s'.", pid));
        return;
    }

    try {
        // trying to find a proper icon
        final int[] sizes = new int[] { 16, 32, 64, 128, 256 };

        BufferedImage img = null;
        for (int size : sizes) {
            // trying to find an icon
            InputStream in = ocd.getIcon(size);
            if (in == null) {
                if (size == sizes[sizes.length - 1]) {
                    // fallback to the default image
                    in = this.getClass().getResourceAsStream("/resources/images/cog.png");
                } else
                    continue;
            }

            // loading date
            final ByteArrayOutputStream bout = new ByteArrayOutputStream();
            IOUtils.copy(in, bout);
            bout.close();
            in.close();

            // trying to detect the mimetype of the image
            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
            String contentType = URLConnection.guessContentTypeFromStream(bin);
            bin.close();

            Iterator<ImageReader> readers = null;
            if (contentType != null) {
                readers = ImageIO.getImageReadersByMIMEType(contentType);
            } else {
                readers = ImageIO.getImageReadersByFormatName("png");
            }

            while (readers.hasNext() && img == null) {
                // trying the next reader
                final ImageReader reader = readers.next();

                InputStream input = null;
                try {
                    input = new ByteArrayInputStream(bout.toByteArray());
                    reader.setInput(ImageIO.createImageInputStream(input));
                    img = reader.read(0);
                } catch (Exception e) {
                    this.log("Unable to read image for pid " + pid, e);
                } finally {
                    if (input != null)
                        input.close();
                }
            }

            if (img != null) {
                response.setHeader("Content-Type", "image/png");
                ImageIO.write(img, "png", response.getOutputStream());
                return;
            }
        }

        // no icon found. 
        response.sendError(404);
    } catch (Throwable e) {
        response.sendError(404, e.getMessage());
        return;
    }
}

From source file:org.medici.bia.controller.manuscriptviewer.IIPImageServerController.java

/**
 * /*from w  w w .  j  ava  2 s.c  o  m*/
 * @param imageName
 * @param thumbnailWidth
 * @param thumbnailFormat
 * @param response
 */
private void generateThumbnailImage(String imageName, Double thumbnailWidth, Integer imageQuality,
        String thumbnailFormat, HttpServletResponse httpServletResponse) {
    File imageFile = new File(
            ApplicationPropertyManager.getApplicationProperty("iipimage.image.path") + imageName);

    ImageInputStream imageInputStream = null;
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    InputStream inputStream = null;

    try {
        if (imageFile.canRead()) {
            // Reading complete tiff information
            imageInputStream = ImageIO.createImageInputStream(imageFile);
        } else {
            logger.error("File " + imageFile.toString() + " is not present on filesystem. ");
            imageFile = new File(ApplicationPropertyManager.getApplicationProperty("iipimage.image.path")
                    + ApplicationPropertyManager.getApplicationProperty("iipimage.image.notavailable"));
            if (imageFile.canRead()) {
                // Reading complete tiff information
                imageInputStream = ImageIO.createImageInputStream(imageFile);
            } else {
                logger.error("File " + imageFile.toString() + " is not present on filesystem. ");
            }
        }

        if (imageInputStream != null) {
            Iterator<ImageReader> readers = ImageIO.getImageReaders(imageInputStream);
            if (readers.hasNext()) {
                ImageReader reader = readers.next();
                reader.setInput(imageInputStream, false, true);

                BufferedImage page = null;
                if (reader.getNumImages(true) <= 2) {
                    logger.error(imageFile + " have " + reader.getNumImages(true)
                            + " level. Trying to render thumbnail image from level 1");
                    page = reader.read(0);
                } else {
                    page = reader.read(2);
                }

                if (page != null) {
                    RenderedOp thubmnailImage = null;
                    try {
                        double resizeFactor = thumbnailWidth / page.getWidth();

                        if (resizeFactor <= 1) {
                            ParameterBlock paramBlock = new ParameterBlock();
                            paramBlock.addSource(page); // The source image
                            paramBlock.add(resizeFactor); // The xScale
                            paramBlock.add(resizeFactor); // The yScale
                            paramBlock.add(0.0); // The x translation
                            paramBlock.add(0.0); // The y translation
                            RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING,
                                    RenderingHints.VALUE_RENDER_QUALITY);
                            thubmnailImage = JAI.create("SubsampleAverage", paramBlock, qualityHints);
                        } else if (resizeFactor > 1) {
                            thubmnailImage = ScaleDescriptor.create(page, (float) resizeFactor,
                                    (float) resizeFactor, 0.0f, 0.0f,
                                    Interpolation.getInstance(Interpolation.INTERP_BICUBIC), null);
                        }

                        if ((thumbnailFormat != null) && (thumbnailFormat.toLowerCase().equals("jpeg"))) {
                            // replaced statement to control jpeg quality
                            // ImageIO.write(thubmnailImage, "jpeg",
                            // byteArrayOutputStream);
                            JPEGEncodeParam jpgparam = new JPEGEncodeParam();
                            jpgparam.setQuality(imageQuality);
                            ImageEncoder enc = ImageCodec.createImageEncoder("jpeg", byteArrayOutputStream,
                                    jpgparam);
                            enc.encode(thubmnailImage);
                        } else {
                            logger.error("Unmanaged thumbnail format " + thumbnailFormat);
                        }
                    } catch (IOException ioException) {
                        logger.error(ioException);
                    }
                }

                // preparing image for output
                inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

                // writing image to output
                httpServletResponse.setContentType("image/jpeg");
                IOUtils.copy(inputStream, httpServletResponse.getOutputStream());

                // Flushing request
                httpServletResponse.getOutputStream().flush();
            }
        } else {
            logger.error("File " + imageFile.toString() + " is not present on filesystem.");
        }
    } catch (IIOException iioException) {
        if (iioException.getMessage().equals("Unsupported Image Type")) {
            logger.error("Unsupported Image Type " + imageFile);
        } else {
            logger.error(iioException);
        }
    } catch (IOException ioException) {
        logger.error(ioException);
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException ioException) {
        }
        try {
            if (byteArrayOutputStream != null) {
                byteArrayOutputStream.close();
            }
        } catch (IOException ioException) {
        }
        try {
            if (imageInputStream != null) {
                imageInputStream.close();
            }
        } catch (IOException ioException) {
        }
    }
}

From source file:org.hippoecm.frontend.plugins.gallery.imageutil.ScaleImageOperation.java

private BufferedImage getScaledImage(final ImageReader reader, final int originalWidth,
        final int originalHeight) throws IOException {

    final double resizeRatio = calculateResizeRatio(originalWidth, originalHeight, width, height);

    int targetWidth;
    int targetHeight;

    if (resizeRatio >= 1.0d && !upscaling) {
        targetWidth = originalWidth;//from  w  w w.  j a v  a2s . com
        targetHeight = originalHeight;
    } else {
        // scale the image
        targetWidth = (int) Math.max(originalWidth * resizeRatio, 1);
        targetHeight = (int) Math.max(originalHeight * resizeRatio, 1);
    }
    if (log.isDebugEnabled()) {
        log.debug("Resizing image of {}x{} to {}x{}", originalWidth, originalHeight, targetWidth, targetHeight);
    }

    BufferedImage scaledImage;

    synchronized (scalingLock) {
        BufferedImage originalImage = reader.read(0);
        scaledImage = ImageUtils.scaleImage(originalImage, targetWidth, targetHeight, strategy);
    }
    return scaledImage;
}

From source file:net.filterlogic.util.imaging.ToTIFF.java

/**
 * /*from  w  w w  . j  a  v  a  2 s.  c o  m*/
 * @param fileName
 */
public void test6(String fileName) {
    try {
        File f = new File(fileName);

        ImageInputStream imageInputStream = ImageIO.createImageInputStream(f);
        java.util.Iterator readers = ImageIO.getImageReaders(imageInputStream);
        ImageReader reader1 = (ImageReader) readers.next();
        ImageInputStream iis = ImageIO.createImageInputStream(new FileInputStream(f));
        reader1.setInput(iis);

        int number = reader1.getNumImages(true);
        Iterator writers = ImageIO.getImageWritersByFormatName("tiff");
        ImageWriter writer = (ImageWriter) writers.next();

        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ImageOutputStream ios = null;
        BufferedImage img = null;

        for (int i = 0; i < number; i++) {
            img = reader1.read(i);
            ios = ImageIO.createImageOutputStream(byteOut);
            writer.setOutput(ios);
            writer.write(img);
            ios.flush();
            img.flush();
            byteOut.flush();
        }

    } catch (Exception e) {
        System.out.println(e.toString());
    }

}

From source file:nl.b3p.viewer.image.ImageTool.java

/** Reads an image from an http input stream.
 *
 * @param method Apache HttpClient GetMethod object
 * @param mime String representing the mime type of the image.
 *
 * @return BufferedImage/*  ww  w  .  java  2s  .  c  o m*/
 *
 * @throws Exception
 */
// <editor-fold defaultstate="" desc="readImage(GetMethod method, String mime) method.">
public static BufferedImage readImage(HttpMethod method, String mime) throws Exception {
    ImageReader ir = null;
    BufferedImage i = null;
    try {
        if (mime.indexOf(";") != -1) {
            mime = mime.substring(0, mime.indexOf(";"));
        }
        String mimeType = getMimeType(mime);

        /* TODO: Kijken waarom er geen mime type meer binnenkomt. Wellicht door de 
         * HttpClient vernieuwing in kaartenbalie ? */
        if (mimeType == null) {
            mimeType = "image/png";
        }

        if (mimeType == null) {
            log.error("Response from server not understood (mime = " + mime + "): "
                    + method.getResponseBodyAsString());
            throw new Exception("Response from server not understood (mime = " + mime + "): "
                    + method.getResponseBodyAsString());
        }

        ir = getReader(mimeType);
        if (ir == null) {
            log.error("no reader available for imageformat: "
                    + mimeType.substring(mimeType.lastIndexOf("/") + 1));
            throw new Exception("no reader available for imageformat: "
                    + mimeType.substring(mimeType.lastIndexOf("/") + 1));
        }
        //TODO Make smarter.. Possibly faster... But keep reporting!
        InputStream is = method.getResponseBodyAsStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int bytesRead = 0;
        byte[] buffer = new byte[2048];
        while (bytesRead != -1) {
            bytesRead = is.read(buffer, 0, buffer.length);
            if (bytesRead > 0) {
                baos.write(buffer, 0, bytesRead);
            }
        }
        ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(baos.toByteArray()));
        ir.setInput(stream, true);
        i = ir.read(0);
        //if image is a png, has no alpha and has a tRNS then make that color transparent.
        if (!i.getColorModel().hasAlpha() && ir.getImageMetadata(0) instanceof PNGMetadata) {
            PNGMetadata metadata = (PNGMetadata) ir.getImageMetadata(0);
            if (metadata.tRNS_present) {
                int alphaPix = (metadata.tRNS_red << 16) | (metadata.tRNS_green << 8) | (metadata.tRNS_blue);
                BufferedImage tmp = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_INT_ARGB);
                for (int x = 0; x < i.getWidth(); x++) {
                    for (int y = 0; y < i.getHeight(); y++) {
                        int rgb = i.getRGB(x, y);
                        rgb = (rgb & 0xFFFFFF) == alphaPix ? alphaPix : rgb;
                        tmp.setRGB(x, y, rgb);
                    }
                }
                i = tmp;
            }
        }
    } finally {
        if (ir != null) {
            ir.dispose();
        }
    }
    return i;
}

From source file:org.n52.v3d.terrainserver.povraywts.WebTerrainServlet.java

private BufferedImage prepareImage(ImageInputStream pImageIn, int pHeight, int pWidth, VgElevationGrid pTerrain,
        double pPitch, double pYaw, double pDistance, double pExaggeration, boolean pDrawNorthArrow,
        boolean pHints) {
    BufferedImage lImage = null;/*from  www .ja  v a2  s.  c  om*/
    Iterator iter = ImageIO.getImageReaders(pImageIn); // liefert PNG-ImageReader
    ImageReader reader = (ImageReader) iter.next();
    reader.setInput(pImageIn, true); // seek forward only?

    boolean ready = false;
    int lMaxIntervalChecks = 40;
    long lCheckInterval = mRendererTimeout / lMaxIntervalChecks;
    int ct = 0;
    while ((!ready) && (ct < lMaxIntervalChecks)) {
        try {
            lImage = reader.read(0);
            ready = true;
        } catch (IOException e) {
            ct++;
            try {
                Thread.sleep(lCheckInterval);
            } catch (Exception e2) {
            }
            ;
        }
    }
    if (!ready)
        throw new T3dException("An I/O exception occured. The renderer did not generate an image file.", 403);

    // Copyright-Text und Nordpfeil ergnzen:
    this.addAnnotations(lImage, pHeight, pWidth, pPitch, pYaw, pDrawNorthArrow);
    // Ggf. weitere Information (Hints) ergnzen:
    if (pHints)
        this.addHints(lImage, pTerrain, pDistance, pYaw, pExaggeration);

    return lImage;
}

From source file:net.filterlogic.util.imaging.ToTIFF.java

/**
 * Convert multipage TIFF to single page TIFF.
 * @param srcFiles Array of source files to convert.
 * @param destPath Folder to store single page TIFFs in.
 * @param archivePath Path to move source TIFF files to after single page TIFFs created.
 * @param pattern Pattern of single page TIFF file names.  Java NumberFormatter used with page number to create file name.
 * @param multipage Set to true if source TIFFs should be coverted to multi-page TIFF.
 * @param dpi DPI to set TIFFs to.//  ww  w . j a va  2s .c  o m
 * @return Returns a list of files in destination path.
 * @throws net.filterlogic.util.imaging.OpenCaptureImagingException
 */
public static List toTIFF(String[] srcFiles, String destPath, String archivePath, String pattern,
        boolean multipage, int dpi) throws OpenCaptureImagingException {
    String pathSep = System.getProperty("file.separator");
    boolean jaiSupport = true;

    int pageCount = 0;
    int fileNameCount = 0;

    byte[] imageData = null;

    // make sure destpath has trailing slash.
    if (destPath.lastIndexOf(pathSep) != destPath.length() - 1)
        destPath += pathSep;

    // create path if doesn't exist
    if (!Path.ValidatePath(destPath))
        if (!Path.createPath(destPath))
            throw new OpenCaptureImagingException(
                    "Unable to create destination path for imported images [" + destPath + "]");

    // make sure archivePath has trailing slash
    if (archivePath.lastIndexOf(pathSep) != archivePath.length() - 1)
        archivePath += pathSep;

    if (!Path.ValidatePath(archivePath))
        if (!Path.createPath(archivePath))
            throw new OpenCaptureImagingException(
                    "Unable to create archive path for imported images [" + archivePath + "]");

    // set a default pattern if one not passed.
    if (pattern.trim().length() < 1)
        pattern = "#";

    NumberFormat formatter = new DecimalFormat(pattern);

    ArrayList<String> list = new ArrayList<String>();

    for (int i = 0; i < srcFiles.length; i++) {
        try {

            File f = new File(srcFiles[i]);
            imageData = null;

            ImageIO.setUseCache(false);
            ImageInputStream imageInputStream = ImageIO.createImageInputStream(f);
            java.util.Iterator readers = ImageIO.getImageReaders(imageInputStream);

            ImageReader reader1 = null;

            if (readers.hasNext()) {
                reader1 = (ImageReader) readers.next();
                jaiSupport = true;
            } else
                jaiSupport = false;

            if (jaiSupport) {
                //ImageInputStream iis = ImageIO.createImageInputStream(new FileInputStream(f));
                reader1.setInput(imageInputStream);

                pageCount = reader1.getNumImages(true);
            } else {
                String newFileName = bigEndian2LittleEndian(f.getAbsolutePath());

                if (imageInputStream != null) {
                    imageInputStream.flush();
                    imageInputStream.close();

                    reader1.setInput(imageInputStream);
                    pageCount = reader1.getNumImages(true);

                }

                imageInputStream = ImageIO.createImageInputStream(new File(newFileName));

                readers = ImageIO.getImageReaders(imageInputStream);

            }
            //                Iterator writers = ImageIO.getImageWritersByFormatName("tiff");
            //                ImageWriter writer = (ImageWriter)writers.next();

            //ImageWriteParam param = writer.getDefaultWriteParam();

            //param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

            //String[] legalTypes = param.getCompressionTypes();

            //param.setCompressionType("PackBits");

            //ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            ImageOutputStream ios = null;
            BufferedImage img = null;

            // break out each page to single file
            for (int t = 0; t < pageCount; t++) {

                // format filenumber
                String tifName = destPath + formatter.format(fileNameCount) + ".tif";

                while (new File(tifName).exists()) {
                    tifName = destPath + formatter.format(++fileNameCount) + ".tif";
                }

                FileOutputStream file = new FileOutputStream(new File(tifName));

                if (jaiSupport) {
                    img = reader1.read(t);
                    IIOImage iioimg = reader1.readAll(t, null);
                    //ios = ImageIO.createImageOutputStream(file);
                    //IIOMetadata iiom = getMetadata(writer, img, null, 200);
                } else {
                    img = loadTIFF(imageData, t);
                }
                TIFFEncodeParam tep = setEncoder(TIFFEncodeParam.COMPRESSION_PACKBITS, 200);

                ImageEncoder encoder = ImageCodec.createImageEncoder("TIFF", file, tep);

                encoder.encode(img);
                //boolean ok = ImageIO.write(img, "tiff", ios);
                //writer.setOutput(ios);
                //writer.write(iiom, iioimg, null);

                img.flush();

                //ios.flush();
                //ios.close();
                // ios = null;
                //iioimg = null;
                //iiom = null;
                img = null;
                //writer.dispose();
                //byteOut.flush();
                file.close();

                file = null;

                //System.out.println("Add file!");

                list.add(tifName);
            }

            if (jaiSupport) {
                reader1.dispose();
            }

            readers = null;

            //                writer.dispose();
            //                writers = null;

            imageInputStream.flush();
            imageInputStream.close();
            imageInputStream = null;

            f = null;

            // move file with overwrite
            if (!net.filterlogic.io.FileAccess.Move(srcFiles[i], archivePath, true))
                throw new Exception("Unable to move input file to archive path [" + srcFiles[i] + "] to ["
                        + archivePath + "]");

        } catch (Exception e) {
            throw new OpenCaptureImagingException(e.toString());
        }
    }

    return list;
}

From source file:com.sketchy.utils.image.SketchyImage.java

public static SketchyImage load(File file) throws Exception {
    SketchyImage sketchyImage = null;//from   w  ww .  j a va 2  s. com

    if (!file.exists() || !file.canRead()) {
        throw new Exception("Can not find or read File: " + file.getPath() + "!");
    }

    if (!StringUtils.endsWithIgnoreCase(file.getName(), ".png")) {
        throw new Exception("Can not load SketchyImage! Must be a .png file!");
    }

    Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName("png");
    ImageReader imageReader = null;
    if (imageReaders.hasNext()) { // Just get first one
        imageReader = imageReaders.next();
    }
    if (imageReader == null) {
        // this should never happen!! if so.. we got problems
        throw new Exception("Can not find ImageReader for .png Files!");
    }

    ImageInputStream is = null;
    try {
        is = ImageIO.createImageInputStream(file);
        imageReader.setInput(is, true);
        IIOMetadata metaData = imageReader.getImageMetadata(0); // always get first image
        IIOMetadataNode metaDataNode = (IIOMetadataNode) metaData
                .getAsTree(metaData.getNativeMetadataFormatName());
        if (metaDataNode == null) {
            throw new Exception("Error retreiving MetaData properties from .png File!");
        }

        NodeList childNodes = metaDataNode.getElementsByTagName("pHYs");
        // only look in the first node
        if (childNodes.getLength() == 0) {
            throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnit' MetaData!");
        }
        IIOMetadataNode physNode = (IIOMetadataNode) childNodes.item(0);
        String pixelsPerUnitXAxisAttribute = physNode.getAttribute("pixelsPerUnitXAxis");
        String pixelsPerUnitYAxisAttribute = physNode.getAttribute("pixelsPerUnitYAxis");
        // String unitSpecifierAttribute = physNode.getAttribute("unitSpecifier"); Just assuming meter
        if (StringUtils.isBlank(pixelsPerUnitXAxisAttribute)) {
            throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnitXAxis' MetaData!");
        }
        if (StringUtils.isBlank(pixelsPerUnitYAxisAttribute)) {
            throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnitYAxis' MetaData!");
        }

        int pixelsPerUnitXAxis;
        try {
            pixelsPerUnitXAxis = Integer.parseInt(pixelsPerUnitXAxisAttribute);
            if (pixelsPerUnitXAxis <= 0)
                throw new Exception("Value must be > 0");
        } catch (Exception e) {
            throw new Exception("Invalid 'pixelsPerUnitXAxis' MetaData Attribute! " + e.getMessage());
        }

        int pixelsPerUnitYAxis;
        try {
            pixelsPerUnitYAxis = Integer.parseInt(pixelsPerUnitYAxisAttribute);
            if (pixelsPerUnitYAxis <= 0)
                throw new Exception("Value must be > 0");
        } catch (Exception e) {
            throw new Exception("Invalid 'pixelsPerUnitYAxis' MetaData Attribute! " + e.getMessage());
        }

        // We successfully processed the MetaData.. now read/set the image 
        BufferedImage bufferedImage = imageReader.read(0); // always get first image

        double xPixelsPerMM = pixelsPerUnitXAxis / 1000.0;
        double yPixelsPerMM = pixelsPerUnitYAxis / 1000.0;

        sketchyImage = new SketchyImage(bufferedImage, xPixelsPerMM, yPixelsPerMM);
    } catch (Exception e) {
        throw new Exception("Error Loading SketchyImage File: " + file.getPath() + "! " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(is);
    }

    return sketchyImage;
}