Example usage for javax.imageio.stream ImageInputStream close

List of usage examples for javax.imageio.stream ImageInputStream close

Introduction

In this page you can find the example usage for javax.imageio.stream ImageInputStream close.

Prototype

void close() throws IOException;

Source Link

Document

Closes the stream.

Usage

From source file:org.photovault.imginfo.ImageFile.java

/**
 *     Opens the image file specified by fname & dirname properties, read
 *     the rest of fields from that and create the instances
 * @param f File from which to read the information
 * @throws org.photovault.common.PhotovaultException If the file is not of recognized type
 * @throws IOException if the image cannot be read.
 */// w ww.j av  a  2s . c om
protected void readImageFile(File f) throws PhotovaultException, IOException {

    String fname = f.getName();
    int lastDotPos = fname.lastIndexOf(".");
    if (lastDotPos <= 0 || lastDotPos >= fname.length() - 1) {
        throw new PhotovaultException("Cannot determine file type extension of " + f.getAbsolutePath());
    }
    String suffix = fname.substring(lastDotPos + 1);
    Iterator readers = ImageIO.getImageReadersBySuffix(suffix);
    if (readers.hasNext()) {
        ImageReader reader = (ImageReader) readers.next();
        ImageInputStream iis = null;
        try {
            iis = ImageIO.createImageInputStream(f);
            if (iis != null) {
                reader.setInput(iis, true);
                // int imageCount = reader.getNumImages( true );
                // for now...
                int imageCount = 1;
                for (int n = 0; n < imageCount; n++) {
                    ImageDescriptorBase img = new OriginalImageDescriptor(this, "image#" + n);
                    img.setWidth(reader.getWidth(n));
                    img.setHeight(reader.getHeight(n));
                    // img.setInstanceType( ImageInstance.INSTANCE_TYPE_ORIGINAL );
                    img.setFile(this);
                }
                reader.dispose();
            }
        } catch (IOException ex) {
            log.debug("Exception in readImageFile: " + ex.getMessage());
            throw ex;
        } finally {
            if (iis != null) {
                try {
                    iis.close();
                } catch (IOException ex) {
                    log.warn("Cannot close image stream: " + ex.getMessage());
                }
            }
        }
    } else {
        RawImage ri = new RawImage(f);
        if (ri.isValidRawFile()) {
            // PlanarImage img = ri.getCorrectedImage();
            ImageDescriptorBase img = new OriginalImageDescriptor(this, "image#0");
            img.setWidth(ri.getWidth());
            img.setHeight(ri.getHeight());
        } else {
            throw new PhotovaultException(
                    "Unknown image file extension " + suffix + "\nwhile reading " + f.getAbsolutePath());
        }
    }

}

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

/**
 * Creates a scaled version of an image. The given scaling parameters define a bounding box with a certain width and
 * height. Images that do not fit in this box (i.e. are too large) are always scaled down such that they do fit. If
 * the aspect ratio of the original image differs from that of the bounding box, either the width or the height of
 * scaled image will be less than that of the box.</p> <p> Smaller images are scaled up in the same way as large
 * images are scaled down, but only if upscaling is true. When upscaling is false and the image is smaller than the
 * bounding box, the scaled image will be equal to the original.</p> <p> If the width or height of the scaling
 * parameters is 0 or less, that side of the bounding box does not exist (i.e. is unbounded). If both sides of the
 * bounding box are unbounded, the scaled image will be equal to the original.</p>
 *
 * @param data   the original image data
 * @param reader reader for the image data
 * @param writer writer for the image data
 */// w  w  w. ja  v a 2s  .c  om
public void execute(InputStream data, ImageReader reader, ImageWriter writer) throws IOException {
    // save the image data in a temporary file so we can reuse the original data as-is if needed without
    // putting all the data into memory
    final File tmpFile = writeToTmpFile(data);
    boolean deleteTmpFile = true;
    log.debug("Stored uploaded image in temporary file {}", tmpFile);

    InputStream dataInputStream = null;
    ImageInputStream imageInputStream = null;

    try {
        dataInputStream = new FileInputStream(tmpFile);
        imageInputStream = new MemoryCacheImageInputStream(dataInputStream);
        reader.setInput(imageInputStream);

        final int originalWidth = reader.getWidth(0);
        final int originalHeight = reader.getHeight(0);

        if (isOriginalVariant()) {
            scaledWidth = originalWidth;
            scaledHeight = originalHeight;
            scaledData = new AutoDeletingTmpFileInputStream(tmpFile);
            deleteTmpFile = false;
        } else {
            BufferedImage scaledImage = getScaledImage(reader, originalWidth, originalHeight);
            ByteArrayOutputStream scaledOutputStream = ImageUtils.writeImage(writer, scaledImage,
                    compressionQuality);

            scaledWidth = scaledImage.getWidth();
            scaledHeight = scaledImage.getHeight();
            scaledData = new ByteArrayInputStream(scaledOutputStream.toByteArray());
        }
    } finally {
        if (imageInputStream != null) {
            imageInputStream.close();
        }
        IOUtils.closeQuietly(dataInputStream);
        if (deleteTmpFile) {
            log.debug("Deleting temporary file {}", tmpFile);
            tmpFile.delete();
        }
    }
}

From source file:org.n52.v3d.terrainserver.profileservice.ProfileServlet.java

/**
 * bearbeitet HTTP-Get-Anfragen an das Servlet.<p>
 * @param pRequest HTTP-Anfrage-Objekt/*from  w  ww  .  ja va  2 s .c  o m*/
 * @param pResponse HTTP-Antwort-Objekt
 * @throws ServletException
 * @throws IOException
 */
public void doGet(HttpServletRequest pRequest, HttpServletResponse pResponse)
        throws ServletException, IOException {
    T3dTimeList lTimeProt = new T3dTimeList(); // zur Protokollierung der Rechenzeiten
    lTimeProt.addTimeStamp("init");

    // Eindeutigen Temporrdatei-Rumpf fr aktuelle Anfrage festlegen:
    String lTmpName = "~" + (mCounter++) + "_" + new java.util.Date().getTime();

    try {
        // Request-Parameter holen:
        HttpRequestParams lReqParams = this.fetchRequestParameters(pRequest);
        String lRequest = (String) lReqParams.getParameterValue("REQUEST");
        VgLineString lDefLine = (VgLineString) lReqParams.getParameterValue("DEFLINE");
        String lSRS = (String) lReqParams.getParameterValue("SRS");
        String lFormat = (String) lReqParams.getParameterValue("FORMAT");
        int lWidth = ((Integer) lReqParams.getParameterValue("WIDTH")).intValue();
        int lHeight = ((Integer) lReqParams.getParameterValue("HEIGHT")).intValue();
        double lExaggeration = ((Double) lReqParams.getParameterValue("EXAGGERATION")).doubleValue(); // todo sinnvoll?
        //int lVisAdds = ((Integer) lReqParams.getParameterValue("VISADDS")).intValue();
        VgPoint lPoint = (VgPoint) lReqParams.getParameterValue("POINT");

        if (lRequest.equalsIgnoreCase("GetCapabilities")) {
            HttpStandardResponse response = new HttpStandardResponse();
            response.sendXMLFile(mCapabilitiesFile, pResponse); // todo: serverrun/Capabilities.xml einrichten und web.xml-Additions
            this.logGetCapabilitiesInfo(lTmpName, pRequest);
            return;
        }

        if (!(lRequest.equalsIgnoreCase("GetGraph") || lRequest.equalsIgnoreCase("GetElevation")))
            throw new T3dException("Illegal request type " + lRequest + "...");

        // Request-Parameter aufbereiten und Wertebereiche prfen:
        ParameterPreparer pp = new ParameterPreparer();
        lSRS = pp.prepareSRS(lSRS);
        lFormat = pp.prepareFORMAT(lFormat, lRequest);
        if (lRequest.equalsIgnoreCase("GetGraph")) {
            lWidth = pp.prepareWIDTH(lWidth);
            lHeight = pp.prepareHEIGHT(lHeight);
        }
        if (lRequest.equalsIgnoreCase("GetElevation")) {
            String str = "" + lPoint.getX() + "," + lPoint.getY()
                    + ",0.0," /* erster Eckpunkt = Interpolationspunkt */
                    + lPoint.getX() + "," + lPoint.getY() + ",0.0"; /* zweiter Eckpunkt als Hilfspunkt */
            lDefLine = new GmLineString(str);
            if (lPoint instanceof VgPoint) {
                lPoint.setSRS(lSRS);
            }
        }

        sLogger.debug("ProfileServlet (" + lTmpName + "): Received " + lRequest + " request.");
        lTimeProt.setFinished("init");

        // Hhenmodell berechnen (Gridding):
        lTimeProt.addTimeStamp("dem_access");
        final boolean lDebug = false; // todo: auf 'false' setzen
        if (lDebug)
            System.out.println("lDefLine = " + lDefLine);
        VgEnvelope lBBox = lDefLine.envelope();
        lBBox.setSRS(lSRS);
        lBBox = this.assureBBoxExtent(lBBox);
        if (lDebug)
            System.out.println("lBBox = " + lBBox);
        GmSimpleElevationGrid lTerrain = this.setUpTerrain(lBBox);
        if (lDebug) {
            System.out.println("lTerrain = " + lTerrain);
            System.out.println("lTerrain.envelope = " + lTerrain.getGeometry().envelope());
        }
        lTimeProt.setFinished("dem_access");

        // Profil generieren:
        lTimeProt.addTimeStamp("profile_generation");
        FltElevationGrid2Profile lProc = new FltElevationGrid2Profile();
        VgProfile lProfile = lProc.transform(lTerrain, lDefLine);
        lTimeProt.setFinished("profile_generation");

        if (lRequest.equalsIgnoreCase("GetGraph")) {
            // Ergebnisbild generieren:
            lTimeProt.addTimeStamp("rendering");
            IoProfileWriter lWriter = new IoProfileWriter("SVG"); // stets SVG generieren
            String lResFile = mWorkingDirectory + "/" + lTmpName + ".svg";
            lWriter.writeToFile(lProfile, lResFile);
            boolean lSendAsPngImage = false;
            String lResFilePng = "";
            if (lFormat.equalsIgnoreCase("image/png"))
                lSendAsPngImage = true;
            if (lSendAsPngImage) {
                PNGTranscoder lTranscoder = new PNGTranscoder();
                String lSvgURI = new File(lResFile).toURL().toString();
                TranscoderInput lInput = new TranscoderInput(lSvgURI);
                lResFilePng = mWorkingDirectory + "/" + lTmpName + ".png";
                OutputStream lOStream = new FileOutputStream(lResFilePng);
                TranscoderOutput lOutput = new TranscoderOutput(lOStream);
                lTranscoder.transcode(lInput, lOutput);
                lOStream.flush();
                lOStream.close();
            }
            lTimeProt.setFinished("rendering");

            // Ergebnisbild als Antwort senden:
            lTimeProt.addTimeStamp("send_response");
            if (!lSendAsPngImage) {
                pResponse.setContentType("image/svg+xml"); // MIME-Typ fr Antwort setzen
                BufferedReader lDatRead;
                try {
                    lDatRead = new BufferedReader(new FileReader(lResFile));
                } catch (FileNotFoundException e) {
                    throw new T3dException("Internal error while reading \"" + lResFile + "\".");
                }
                PrintWriter out = pResponse.getWriter(); // PrintWriter auf die Antwort aufsetzen
                String line = lDatRead.readLine();
                while (line != null) { // generierte Temporrdatei zeilenweise senden
                    out.println(line);
                    line = lDatRead.readLine();
                }
                lDatRead.close();
                out.flush();
                out.close();
            } else {
                // Bild senden (vgl. Code aus WebTerrainServlet:
                try {
                    File f = new File(lResFilePng);
                    ImageInputStream is = ImageIO.createImageInputStream(f);
                    Iterator iter = ImageIO.getImageReaders(is); // liefert PNG-ImageReader
                    ImageReader reader = (ImageReader) iter.next();
                    reader.setInput(is, true); // seek forward only?
                    BufferedImage lImage = reader.read(0);

                    OutputStream out = pResponse.getOutputStream();
                    ImageIO.setUseCache(false); // wichtig!
                    pResponse.setContentType(lFormat); // MIME-Typ fr Antwort setzen
                    String resExt = MimeTypeHelper.getFileExtension(lFormat);
                    try {
                        ImageIO.write(lImage, resExt, out); // resExt ist informaler Formatname...
                    } catch (Exception e) {
                        throw new T3dException("Did not finish PNG image send process. " + e.getMessage(), 103); // todo fehler-nr. prfen und in doku
                    }
                    is.close();
                    out.close();
                } catch (IOException e) {
                    throw new T3dException(
                            "An I/O exception occured. The servlet could not send an image reponse.", 106); // todo fehler-nr. prfen und in doku
                }
            }
            File fSvg = new File(lResFile);
            fSvg.delete();
            if (lSendAsPngImage) {
                File fPng = new File(lResFilePng);
                fPng.delete();
            }
            lTimeProt.setFinished("send_response");
        } else {
            if (lRequest.equalsIgnoreCase("GetElevation")) {
                lTimeProt.addTimeStamp("send_response");
                double x, y, z;
                try {
                    x = ((VgLineString) (lProfile.getGeometry())).getVertex(0).getX(); // = lPoint.getX()
                    y = ((VgLineString) (lProfile.getGeometry())).getVertex(0).getY(); // = lPoint.getY()
                    z = (lProfile.getTZPair(0))[1];
                } catch (Throwable e) {
                    throw new T3dException("No elevation information available.");
                }

                // Antwort senden:
                short lCase = 0;
                if (lFormat.equalsIgnoreCase("text/plain"))
                    lCase = 1;
                if (lFormat.equalsIgnoreCase("text/xml"))
                    lCase = 2;
                if (lFormat.equalsIgnoreCase("text/html"))
                    lCase = 3;
                if (lFormat.equalsIgnoreCase("text/comma-separated-values"))
                    lCase = 4;
                if (lCase <= 0)
                    throw new T3dException("Internal servlet error."); // Kann nicht auftreten
                pResponse.setContentType(lFormat); // MIME-Typ fr Antwort setzen
                PrintWriter out = pResponse.getWriter(); // PrintWriter auf die Antwort aufsetzen
                switch (lCase) {
                case 1:
                    out.println("Position:");
                    out.println("SRS: " + lPoint.getSRS()); // = lSRS
                    out.println("X = " + x);
                    out.println("Y = " + y);
                    out.println("");
                    out.println("Elevation = " + z);
                    break;
                case 2:
                    out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\" ?>");
                    out.println("<ServiceResponse>");
                    out.println("  <Position>");
                    out.println("    <SRS>" + lPoint.getSRS() + "</SRS>"); // = lSRS
                    out.println("    <X>" + x + "</X>");
                    out.println("    <Y>" + y + "</Y>");
                    out.println("  </Position>");
                    out.println("  <Elevation>" + z + "</Elevation>");
                    out.println("</ServiceResponse>");
                    break;
                case 3:
                    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
                    out.println("<html>");
                    out.println("<head>");
                    out.println("<title>52N terrainServer elevation information</title>");
                    out.println("<font face=\"Verdana, Arial, Helvetica\" size=1>");
                    out.println("<meta http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">");
                    out.println("<body text=#000000 bgColor=#ffffff leftMargin=0 topMargin=0>");
                    out.println("<table border=\"1\">");
                    out.println("<tr><td><b>Position:</b></td><td><br></td></tr>");
                    out.println("<tr><td>SRS:</td><td>" + lPoint.getSRS() + "</td></tr>"); // lPoint.getSRS() = lSRS
                    out.println("<tr><td>X:</td><td>" + x + "<td></tr>");
                    out.println("<tr><td>Y:</td><td>" + y + "<td></tr>");
                    out.println("<tr><td><b>Elevation:</b></td><td>" + z + "<td></tr>");
                    out.println("</table>");
                    out.println("</html>");
                    break;
                case 4:
                    out.println(z);
                    break;
                }
                out.flush();
                out.close();
                lTimeProt.setFinished("send_response");
            }
        }

        //String lOutputFormatInfo = lFormat + " (" + lWidth + "x" + lHeight + ")";
        if (lRequest.equalsIgnoreCase("GetGraph"))
            this.logGetGraphInfo(lTmpName, lTerrain, lDefLine, lTimeProt, pRequest,
                    lFormat /*lOutputFormatInfo*/);
        else {
            if (lRequest.equalsIgnoreCase("GetElevation"))
                this.logGetElevationInfo(lTmpName, lTerrain, lPoint, lTimeProt, pRequest, lFormat);
        }

        sLogger.debug("ProfileServlet (" + lTmpName + "): Duly finished execution.");
    } catch (Throwable e) {
        sLogger.debug("ProfileServlet (" + lTmpName + "): Aborting execution. Error: " + e.getMessage());

        HttpStandardResponse response = new HttpStandardResponse();
        try {
            response.sendException(e.getMessage(), pResponse);
        } catch (Throwable e2) {
            try {
                response.sendException(e.getMessage(), pResponse);
            } catch (Throwable e3) {
                System.out.println("ProfileServlet: FATAL ERROR - " + e3.getMessage());
            }
        }
        try {
            this.logErrorInfo(lTmpName, lTimeProt, pRequest, e);
        } catch (Throwable e2) {
            System.out.println("ProfileServlet: FATAL ERROR - " + e2.getMessage());
        }
    }
}

From source file:org.apache.pdfbox.tools.imageio.TestImageIOUtils.java

/**
 * checks whether the resolution of an image file is as expected.
 *
 * @param filename the name of the file/*  ww w  . j  a v a2s.co  m*/
 * @param expectedResolution the expected resolution
 *
 * @throws IOException if something goes wrong
 */
private void checkResolution(String filename, int expectedResolution) throws IOException {
    assertFalse("Empty file " + filename, new File(filename).length() == 0);
    String suffix = filename.substring(filename.lastIndexOf('.') + 1);
    if ("BMP".equals(suffix.toUpperCase())) {
        // BMP reader doesn't work
        checkBmpResolution(filename, expectedResolution);
        return;
    }
    Iterator readers = ImageIO.getImageReadersBySuffix(suffix);
    assertTrue("No image reader found for suffix " + suffix, readers.hasNext());
    ImageReader reader = (ImageReader) readers.next();
    ImageInputStream iis = ImageIO.createImageInputStream(new File(filename));
    assertNotNull("No ImageInputStream created for file " + filename, iis);
    reader.setInput(iis);
    IIOMetadata imageMetadata = reader.getImageMetadata(0);
    Element root = (Element) imageMetadata.getAsTree(STANDARD_METADATA_FORMAT);
    NodeList dimensionNodes = root.getElementsByTagName("Dimension");
    assertTrue("No resolution found in image file " + filename, dimensionNodes.getLength() > 0);
    Element dimensionElement = (Element) dimensionNodes.item(0);

    NodeList pixelSizeNodes = dimensionElement.getElementsByTagName("HorizontalPixelSize");
    assertTrue("No X resolution found in image file " + filename, pixelSizeNodes.getLength() > 0);
    Node pixelSizeNode = pixelSizeNodes.item(0);
    String val = pixelSizeNode.getAttributes().getNamedItem("value").getNodeValue();
    int actualResolution = (int) Math.round(25.4 / Double.parseDouble(val));
    assertEquals("X resolution doesn't match in image file " + filename, expectedResolution, actualResolution);

    pixelSizeNodes = dimensionElement.getElementsByTagName("VerticalPixelSize");
    assertTrue("No Y resolution found in image file " + filename, pixelSizeNodes.getLength() > 0);
    pixelSizeNode = pixelSizeNodes.item(0);
    val = pixelSizeNode.getAttributes().getNamedItem("value").getNodeValue();
    actualResolution = (int) Math.round(25.4 / Double.parseDouble(val));
    assertEquals("Y resolution doesn't match", expectedResolution, actualResolution);

    iis.close();
    reader.dispose();
}

From source file:org.apache.pdfbox.pdmodel.graphics.shading.PatchMeshesShadingContext.java

/**
 * Create a patch list from a data stream, the returned list contains all the patches contained
 * in the data stream./*ww w  . j av  a2 s.co m*/
 *
 * @param shadingType the shading type
 * @param xform transformation for user to device space
 * @param matrix the pattern matrix concatenated with that of the parent content stream
 * @param controlPoints number of control points, 12 for type 6 shading and 16 for type 7 shading
 * @return the obtained patch list
 * @throws IOException when something went wrong
 */
final List<Patch> collectPatches(PDShadingType6 shadingType, AffineTransform xform, Matrix matrix,
        int controlPoints) throws IOException {
    COSDictionary dict = shadingType.getCOSObject();
    int bitsPerFlag = shadingType.getBitsPerFlag();
    PDRange rangeX = shadingType.getDecodeForParameter(0);
    PDRange rangeY = shadingType.getDecodeForParameter(1);
    PDRange[] colRange = new PDRange[numberOfColorComponents];
    for (int i = 0; i < numberOfColorComponents; ++i) {
        colRange[i] = shadingType.getDecodeForParameter(2 + i);
    }
    List<Patch> list = new ArrayList<Patch>();
    long maxSrcCoord = (long) Math.pow(2, bitsPerCoordinate) - 1;
    long maxSrcColor = (long) Math.pow(2, bitsPerColorComponent) - 1;
    COSStream cosStream = (COSStream) dict;

    ImageInputStream mciis = new MemoryCacheImageInputStream(cosStream.createInputStream());
    try {
        Point2D[] implicitEdge = new Point2D[4];
        float[][] implicitCornerColor = new float[2][numberOfColorComponents];
        byte flag = 0;

        try {
            flag = (byte) (mciis.readBits(bitsPerFlag) & 3);
        } catch (EOFException ex) {
            LOG.error(ex);
        }

        while (true) {
            try {
                boolean isFree = (flag == 0);
                Patch current = readPatch(mciis, isFree, implicitEdge, implicitCornerColor, maxSrcCoord,
                        maxSrcColor, rangeX, rangeY, colRange, matrix, xform, controlPoints);
                if (current == null) {
                    break;
                }
                list.add(current);
                flag = (byte) (mciis.readBits(bitsPerFlag) & 3);
                switch (flag) {
                case 0:
                    break;
                case 1:
                    implicitEdge = current.getFlag1Edge();
                    implicitCornerColor = current.getFlag1Color();
                    break;
                case 2:
                    implicitEdge = current.getFlag2Edge();
                    implicitCornerColor = current.getFlag2Color();
                    break;
                case 3:
                    implicitEdge = current.getFlag3Edge();
                    implicitCornerColor = current.getFlag3Color();
                    break;
                default:
                    LOG.warn("bad flag: " + flag);
                    break;
                }
            } catch (EOFException ex) {
                break;
            }
        }
    } finally {
        mciis.close();
    }
    return list;
}

From source file:org.geotools.utils.imagemosaic.MosaicIndexBuilder.java

/**
 * Main thread for the mosaic index builder.
 *//* ww w .  j a v  a2s  . c o m*/
public void run() {

    // /////////////////////////////////////////////////////////////////////
    //
    // CREATING INDEX FILE
    //
    // /////////////////////////////////////////////////////////////////////

    // /////////////////////////////////////////////////////////////////////
    //
    // Create a file handler that write log record to a file called
    // my.log
    //
    // /////////////////////////////////////////////////////////////////////
    FileHandler handler = null;
    try {
        boolean append = true;
        handler = new FileHandler(new StringBuffer(locationPath).append("/error.txt").toString(), append);
        handler.setLevel(Level.SEVERE);
        // Add to the desired logger
        LOGGER.addHandler(handler);

        // /////////////////////////////////////////////////////////////////////
        //
        // Create a set of file names that have to be skipped since these are
        // our metadata files
        //
        // /////////////////////////////////////////////////////////////////////
        final Set<String> skipFiles = new HashSet<String>(
                Arrays.asList(new String[] { indexName + ".shp", indexName + ".dbf", indexName + ".shx",
                        indexName + ".prj", "error.txt", "error.txt.lck", indexName + ".properties" }));

        // /////////////////////////////////////////////////////////////////////
        //
        // Creating temp vars
        //
        // /////////////////////////////////////////////////////////////////////
        ShapefileDataStore index = null;
        Transaction t = new DefaultTransaction();
        // declaring a preciosion model to adhere the java double type
        // precision
        PrecisionModel precMod = new PrecisionModel(PrecisionModel.FLOATING);
        GeometryFactory geomFactory = new GeometryFactory(precMod);
        try {
            index = new ShapefileDataStore(
                    new File(locationPath + File.separator + indexName + ".shp").toURI().toURL());
        } catch (MalformedURLException ex) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
            fireException(ex);
            return;
        }

        final List<File> files = new ArrayList<File>();
        recurse(files, locationPath);

        // /////////////////////////////////////////////////////////////////////
        //
        // Cycling over the files that have filtered out
        //
        // /////////////////////////////////////////////////////////////////////
        numFiles = files.size();
        String validFileName = null;
        final Iterator<File> filesIt = files.iterator();
        FeatureWriter<SimpleFeatureType, SimpleFeature> fw = null;
        boolean doneSomething = false;
        for (int i = 0; i < numFiles; i++) {

            StringBuffer message;
            // //
            //
            // Check that this file is actually good to go
            //
            // //         
            final File fileBeingProcessed = ((File) filesIt.next());
            if (!fileBeingProcessed.exists() || !fileBeingProcessed.canRead() || !fileBeingProcessed.isFile()) {
                // send a message
                message = new StringBuffer("Skipped file ").append(files.get(i))
                        .append(" snce it seems invalid.");
                if (LOGGER.isLoggable(Level.INFO))
                    LOGGER.info(message.toString());
                fireEvent(message.toString(), ((i * 99.0) / numFiles));
                continue;
            }

            // //
            //
            // Anyone has asked us to stop?
            //
            // //
            if (getStopThread()) {
                message = new StringBuffer("Stopping requested at file  ").append(i).append(" of ")
                        .append(numFiles).append(" files");
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.fine(message.toString());
                }
                fireEvent(message.toString(), ((i * 100.0) / numFiles));
                return;
            } // replacing chars on input path
            try {
                validFileName = fileBeingProcessed.getCanonicalPath();
            } catch (IOException e1) {
                fireException(e1);
                return;
            }
            validFileName = validFileName.replace('\\', '/');
            validFileName = validFileName.substring(locationPath.length() + 1,
                    fileBeingProcessed.getAbsolutePath().length());
            if (skipFiles.contains(validFileName))
                continue;
            message = new StringBuffer("Now indexing file ").append(validFileName);

            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine(message.toString());
            }
            fireEvent(message.toString(), ((i * 100.0) / numFiles));
            try {
                // ////////////////////////////////////////////////////////
                //
                //
                // STEP 1
                // Getting an ImageIO reader for this coverage.
                //
                //
                // ////////////////////////////////////////////////////////
                ImageInputStream inStream = ImageIO.createImageInputStream(fileBeingProcessed);
                if (inStream == null) {
                    if (LOGGER.isLoggable(Level.SEVERE))
                        LOGGER.severe(fileBeingProcessed
                                + " has been skipped since we could not get a stream for it");
                    continue;
                }
                inStream.mark();
                final Iterator<ImageReader> it = ImageIO.getImageReaders(inStream);
                ImageReader r = null;
                if (it.hasNext()) {
                    r = (ImageReader) it.next();
                    r.setInput(inStream);
                } else {
                    // release resources
                    try {
                        inStream.close();
                    } catch (Exception e) {
                        // ignore exception
                    }
                    //               try {
                    //                  r.dispose();
                    //               } catch (Exception e) {
                    //                  // ignore exception
                    //               }

                    // send a message
                    message = new StringBuffer("Skipped file ").append(files.get(i))
                            .append(":No ImageIO readeres avalaible.");
                    if (LOGGER.isLoggable(Level.INFO))
                        LOGGER.info(message.toString());
                    fireEvent(message.toString(), ((i * 99.0) / numFiles));
                    continue;
                }

                // ////////////////////////////////////////////////////////
                //
                // STEP 2
                // Getting a coverage reader for this coverage.
                //
                // ////////////////////////////////////////////////////////
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.fine(new StringBuffer("Getting a reader").toString());
                final AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder
                        .findFormat(files.get(i));
                if (format == null || !format.accepts(files.get(i))) {
                    // release resources
                    try {
                        inStream.close();
                    } catch (Exception e) {
                        // ignore exception
                    }
                    try {
                        r.dispose();
                    } catch (Exception e) {
                        // ignore exception
                    }

                    message = new StringBuffer("Skipped file ").append(files.get(i))
                            .append(": File format is not supported.");
                    if (LOGGER.isLoggable(Level.INFO))
                        LOGGER.info(message.toString());
                    fireEvent(message.toString(), ((i * 99.0) / numFiles));
                    continue;
                }
                final AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) format
                        .getReader(files.get(i));
                envelope = (GeneralEnvelope) reader.getOriginalEnvelope();
                actualCRS = reader.getCrs();

                // /////////////////////////////////////////////////////////////////////
                //
                // STEP 3
                // Get the type specifier for this image and the check that the
                // image has the correct sample model and color model.
                // If this is the first cycle of the loop we initialize
                // eveything.
                //
                // /////////////////////////////////////////////////////////////////////
                final ImageTypeSpecifier its = ((ImageTypeSpecifier) r.getImageTypes(0).next());
                boolean skipFeature = false;
                if (globEnvelope == null) {
                    // /////////////////////////////////////////////////////////////////////
                    //
                    // at the first step we initialize everything that we will
                    // reuse afterwards starting with color models, sample
                    // models, crs, etc....
                    //
                    // /////////////////////////////////////////////////////////////////////
                    defaultCM = its.getColorModel();
                    if (defaultCM instanceof IndexColorModel) {
                        IndexColorModel icm = (IndexColorModel) defaultCM;
                        int numBands = defaultCM.getNumColorComponents();
                        defaultPalette = new byte[3][icm.getMapSize()];
                        icm.getReds(defaultPalette[0]);
                        icm.getGreens(defaultPalette[0]);
                        icm.getBlues(defaultPalette[0]);
                        if (numBands == 4)
                            icm.getAlphas(defaultPalette[0]);

                    }
                    defaultSM = its.getSampleModel();
                    defaultCRS = actualCRS;
                    globEnvelope = new GeneralEnvelope(envelope);

                    // /////////////////////////////////////////////////////////////////////
                    //
                    // getting information about resolution
                    //
                    // /////////////////////////////////////////////////////////////////////

                    // //
                    //
                    // get the dimension of the hr image and build the model
                    // as well as
                    // computing the resolution
                    // //
                    // resetting reader and recreating stream, turnaround for a
                    // strange imageio bug
                    r.reset();
                    try {
                        inStream.reset();
                    } catch (IOException e) {
                        inStream = ImageIO.createImageInputStream(fileBeingProcessed);
                    }
                    //let's check if we got something now
                    if (inStream == null) {
                        //skip file
                        if (LOGGER.isLoggable(Level.WARNING))
                            LOGGER.warning("Skipping file " + fileBeingProcessed.toString());
                        continue;
                    }
                    r.setInput(inStream);
                    numberOfLevels = r.getNumImages(true);
                    resolutionLevels = new double[2][numberOfLevels];
                    double[] res = getResolution(envelope, new Rectangle(r.getWidth(0), r.getHeight(0)),
                            defaultCRS);
                    resolutionLevels[0][0] = res[0];
                    resolutionLevels[1][0] = res[1];

                    // resolutions levels
                    if (numberOfLevels > 1) {

                        for (int k = 0; k < numberOfLevels; k++) {
                            res = getResolution(envelope, new Rectangle(r.getWidth(k), r.getHeight(k)),
                                    defaultCRS);
                            resolutionLevels[0][k] = res[0];
                            resolutionLevels[1][k] = res[1];
                        }
                    }

                    // /////////////////////////////////////////////////////////////////////
                    //
                    // creating the schema
                    //
                    // /////////////////////////////////////////////////////////////////////
                    final SimpleFeatureTypeBuilder featureBuilder = new SimpleFeatureTypeBuilder();
                    featureBuilder.setName("Flag");
                    featureBuilder.setNamespaceURI("http://www.geo-solutions.it/");
                    featureBuilder.add("location", String.class);
                    featureBuilder.add("the_geom", Polygon.class, this.actualCRS);
                    featureBuilder.setDefaultGeometry("the_geom");
                    final SimpleFeatureType simpleFeatureType = featureBuilder.buildFeatureType();
                    // create the schema for the new shape file
                    index.createSchema(simpleFeatureType);

                    // get a feature writer
                    fw = index.getFeatureWriter(t);
                } else {
                    // ////////////////////////////////////////////////////////
                    // 
                    // comparing ColorModel
                    // comparing SampeModel
                    // comparing CRSs
                    // ////////////////////////////////////////////////////////
                    globEnvelope.add(envelope);
                    actualCM = its.getColorModel();
                    actualSM = its.getSampleModel();
                    skipFeature = (i > 0 ? !(CRS.equalsIgnoreMetadata(defaultCRS, actualCRS)) : false);
                    if (skipFeature)
                        LOGGER.warning(new StringBuffer("Skipping image ").append(files.get(i))
                                .append(" because CRSs do not match.").toString());
                    skipFeature = checkColorModels(defaultCM, defaultPalette, actualCM);
                    if (skipFeature)
                        LOGGER.warning(new StringBuffer("Skipping image ").append(files.get(i))
                                .append(" because color models do not match.").toString());
                    // defaultCM.getNumComponents()==actualCM.getNumComponents()&&
                    // defaultCM.getClass().equals(actualCM.getClass())
                    // && defaultSM.getNumBands() == actualSM
                    // .getNumBands()
                    // && defaultSM.getDataType() == actualSM
                    // .getDataType() &&
                    //
                    // if (skipFeature)
                    // LOGGER
                    // .warning(new StringBuffer("Skipping image ")
                    // .append(files.get(i))
                    // .append(
                    // " because cm or sm does not match.")
                    // .toString());
                    // res = getResolution(envelope, new
                    // Rectangle(r.getWidth(0),
                    // r.getHeight(0)), defaultCRS);
                    // if (Math.abs((resX - res[0]) / resX) > EPS
                    // || Math.abs(resY - res[1]) > EPS) {
                    // LOGGER.warning(new StringBuffer("Skipping image
                    // ").append(
                    // files.get(i)).append(
                    // " because resolutions does not match.")
                    // .toString());
                    // skipFeature = true;
                    // }
                }

                // ////////////////////////////////////////////////////////
                //
                // STEP 4
                //
                // create and store features
                //
                // ////////////////////////////////////////////////////////
                if (!skipFeature) {

                    final SimpleFeature feature = fw.next();
                    feature.setAttribute(1,
                            geomFactory.toGeometry(new ReferencedEnvelope((Envelope) envelope)));
                    feature.setAttribute(
                            0, absolute
                                    ? new StringBuilder(this.locationPath).append(File.separatorChar)
                                            .append(validFileName).toString()
                                    : validFileName);
                    fw.write();

                    message = new StringBuffer("Done with file ").append(files.get(i));
                    if (LOGGER.isLoggable(Level.FINE)) {
                        LOGGER.fine(message.toString());
                    }
                    message.append('\n');
                    fireEvent(message.toString(), (((i + 1) * 99.0) / numFiles));
                    doneSomething = true;
                } else
                    skipFeature = false;

                // ////////////////////////////////////////////////////////
                //
                // STEP 5
                //
                // release resources
                //
                // ////////////////////////////////////////////////////////
                try {
                    inStream.close();
                } catch (Exception e) {
                    // ignore exception
                }
                try {
                    r.dispose();
                } catch (Exception e) {
                    // ignore exception
                }
                // release resources
                reader.dispose();

            } catch (IOException e) {
                fireException(e);
                break;
            } catch (ArrayIndexOutOfBoundsException e) {
                fireException(e);
                break;
            }

        }
        try {
            if (fw != null)
                fw.close();
            t.commit();
            t.close();
            index.dispose();
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
        createPropertiesFiles(globEnvelope, doneSomething);
    } catch (SecurityException el) {
        fireException(el);
        return;
    } catch (IOException el) {
        fireException(el);
        return;
    } finally {
        try {
            if (handler != null)
                handler.close();
        } catch (Throwable e) {
            // ignore
        }

    }

}

From source file:org.dita.dost.writer.ImageMetadataFilter.java

private Attributes readMetadata(final URI imgInput) {
    logger.info("Reading " + imgInput);
    final XMLUtils.AttributesBuilder a = new XMLUtils.AttributesBuilder();
    try {//from   w  ww . j  a va2 s.co m
        InputStream in = null;
        ImageReader r = null;
        ImageInputStream iis = null;
        try {
            in = getInputStream(imgInput);
            iis = ImageIO.createImageInputStream(in);
            final Iterator<ImageReader> i = ImageIO.getImageReaders(iis);
            if (!i.hasNext()) {
                logger.info("Image " + imgInput + " format not supported");
            } else {
                r = i.next();
                r.setInput(iis);
                final int imageIndex = r.getMinIndex();
                a.add(DITA_OT_NS, ATTR_IMAGE_WIDTH, DITA_OT_PREFIX + ":" + ATTR_IMAGE_WIDTH, "CDATA",
                        Integer.toString(r.getWidth(imageIndex)));
                a.add(DITA_OT_NS, ATTR_IMAGE_HEIGHT, DITA_OT_PREFIX + ":" + ATTR_IMAGE_HEIGHT, "CDATA",
                        Integer.toString(r.getHeight(imageIndex)));
                final Element node = (Element) r.getImageMetadata(0).getAsTree("javax_imageio_1.0");
                final NodeList hs = node.getElementsByTagName("HorizontalPixelSize");
                if (hs != null && hs.getLength() == 1) {
                    final float v = Float.parseFloat(((Element) hs.item(0)).getAttribute("value"));
                    final int dpi = Math.round(MM_TO_INCH / v);
                    a.add(DITA_OT_NS, ATTR_HORIZONTAL_DPI, DITA_OT_PREFIX + ":" + ATTR_HORIZONTAL_DPI, "CDATA",
                            Integer.toString(dpi));
                }
                final NodeList vs = node.getElementsByTagName("VerticalPixelSize");
                if (vs != null && vs.getLength() == 1) {
                    final float v = Float.parseFloat(((Element) vs.item(0)).getAttribute("value"));
                    final int dpi = Math.round(MM_TO_INCH / v);
                    a.add(DITA_OT_NS, ATTR_VERTICAL_DPI, DITA_OT_PREFIX + ":" + ATTR_VERTICAL_DPI, "CDATA",
                            Integer.toString(dpi));
                }
            }
        } finally {
            if (r != null) {
                r.dispose();
            }
            if (iis != null) {
                iis.close();
            }
            if (in != null) {
                in.close();
            }
        }
    } catch (final Exception e) {
        logger.error("Failed to read image " + imgInput + " metadata: " + e.getMessage(), e);
    }
    return a.build();
}

From source file:net.rptools.tokentool.util.ImageUtil.java

private static ImageView getImage(ImageView thumbView, final Path filePath, final boolean overlayWanted,
        final int THUMB_SIZE) throws IOException {
    Image thumb = null;//from   w w  w  .  j  a v  a  2s .c om
    String fileURL = filePath.toUri().toURL().toString();

    if (ImageUtil.SUPPORTED_IMAGE_FILE_FILTER.accept(null, fileURL)) {
        if (THUMB_SIZE <= 0)
            thumb = processMagenta(new Image(fileURL), COLOR_THRESHOLD, overlayWanted);
        else
            thumb = processMagenta(new Image(fileURL, THUMB_SIZE, THUMB_SIZE, true, true), COLOR_THRESHOLD,
                    overlayWanted);
    } else if (ImageUtil.PSD_FILE_FILTER.accept(null, fileURL)) {
        ImageInputStream is = null;
        PSDImageReader reader = null;
        int imageIndex = 1;

        // Mask layer should always be layer 1 and overlay image on layer 2. Note, layer 0 will be a combined layer composite
        if (overlayWanted)
            imageIndex = 2;

        File file = filePath.toFile();

        try {
            is = ImageIO.createImageInputStream(file);
            if (is == null || is.length() == 0) {
                log.info("Image from file " + file.getAbsolutePath() + " is null");
            }

            Iterator<ImageReader> iterator = ImageIO.getImageReaders(is);
            if (iterator == null || !iterator.hasNext()) {
                throw new IOException("Image file format not supported by ImageIO: " + filePath);
            }

            reader = (PSDImageReader) iterator.next();
            reader.setInput(is);
            BufferedImage thumbBI;
            thumbBI = reader.read(imageIndex);

            if (thumbBI != null) {
                int layerIndex = 0;
                if (overlayWanted)
                    layerIndex = 1;

                IIOMetadata metadata = reader.getImageMetadata(0);
                IIOMetadataNode root = (IIOMetadataNode) metadata
                        .getAsTree(PSDMetadata.NATIVE_METADATA_FORMAT_NAME);
                NodeList layerInfos = root.getElementsByTagName("LayerInfo");

                // Layer index corresponds to imageIndex - 1 in the reader
                IIOMetadataNode layerInfo = (IIOMetadataNode) layerInfos.item(layerIndex);

                // Get the width & height of the Mask layer so we can create the overlay the same size
                int width = reader.getWidth(0);
                int height = reader.getHeight(0);

                // Get layer offsets, PhotoShop PSD layers can have different widths/heights and all images start at 0,0 with a layer offset applied
                int x = Math.max(Integer.parseInt(layerInfo.getAttribute("left")), 0);
                int y = Math.max(Integer.parseInt(layerInfo.getAttribute("top")), 0);

                // Lets pad the overlay with transparency to make it the same size as the PSD canvas size
                thumb = resizeCanvas(SwingFXUtils.toFXImage(thumbBI, null), width, height, x, y);

                // Finally set ImageView to thumbnail size
                if (THUMB_SIZE > 0) {
                    thumbView.setFitWidth(THUMB_SIZE);
                    thumbView.setPreserveRatio(true);
                }
            }
        } catch (Exception e) {
            log.error("Processing: " + file.getAbsolutePath(), e);
        } finally {
            // Dispose reader in finally block to avoid memory leaks
            reader.dispose();
            is.close();
        }
    }

    thumbView.setImage(thumb);

    return thumbView;
}

From source file:com.funambol.foundation.util.MediaUtils.java

/**
 * Creates the thumbnail.//from  www.java  2 s  .c o  m
 *
 * @param imageFile the image file
 * @param thumbFile the empty thumbnail file
 * @param thumbX the width of the thumbnail
 * @param thumbY the height of the thumbnail
 * @param imageName the image file name with extension
 * @param tolerance the percentage of tolerance before creating a thumbnail
 * @return true is the thumbnail has been created, false otherwise
 * @throws IOException if an error occurs
 */
private static boolean createThumbnail(File imageFile, File thumbFile, int thumbX, int thumbY, String imageName,
        double tolerance) throws IOException {

    FileInputStream fileis = null;
    ImageInputStream imageis = null;

    Iterator readers = null;

    try {

        readers = ImageIO.getImageReadersByFormatName(imageName.substring(imageName.lastIndexOf('.') + 1));
        if (readers == null || (!readers.hasNext())) {
            throw new IOException("File not supported");
        }

        ImageReader reader = (ImageReader) readers.next();

        fileis = new FileInputStream(imageFile);
        imageis = ImageIO.createImageInputStream(fileis);
        reader.setInput(imageis, true);

        // Determines thumbnail height, width and quality
        int thumbWidth = thumbX;
        int thumbHeight = thumbY;

        double thumbRatio = (double) thumbWidth / (double) thumbHeight;
        int imageWidth = reader.getWidth(0);
        int imageHeight = reader.getHeight(0);

        //
        // Don't create the thumbnail if the original file is smaller
        // than required size increased by % tolerance
        //
        if (imageWidth <= (thumbWidth * (1 + tolerance / 100))
                && imageHeight <= (thumbHeight * (1 + tolerance / 100))) {

            return false;
        }

        double imageRatio = (double) imageWidth / (double) imageHeight;
        if (thumbRatio < imageRatio) {
            thumbHeight = (int) (thumbWidth / imageRatio);
        } else {
            thumbWidth = (int) (thumbHeight * imageRatio);
        }

        ImageReadParam param = reader.getDefaultReadParam();
        param.setSourceSubsampling(3, 3, 0, 0);

        BufferedImage bi = reader.read(0, param);

        Image thumb = bi.getScaledInstance(thumbWidth, thumbHeight, Image.SCALE_SMOOTH);

        BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(thumb, 0, 0, thumbWidth, thumbHeight, null);

        FileOutputStream fileOutputStream = new FileOutputStream(thumbFile);
        ImageIO.write(thumbImage, "jpg", fileOutputStream);

        thumb.flush();
        thumbImage.flush();
        fileOutputStream.flush();
        fileOutputStream.close();
        graphics2D.dispose();

    } finally {
        if (fileis != null) {
            fileis.close();
        }
        if (imageis != null) {
            imageis.close();
        }
    }

    return true;
}

From source file:org.geotools.gce.imagemosaic.GranuleDescriptor.java

GranuleOverviewLevelDescriptor getLevel(final int index) {

    //load level/*from w  w w  . j a  v  a 2 s .co m*/
    // create the base grid to world transformation
    ImageInputStream inStream = null;
    ImageReader reader = null;
    try {

        // get a stream
        assert cachedStreamSPI != null : "no cachedStreamSPI available!";
        inStream = cachedStreamSPI.createInputStreamInstance(granuleUrl, ImageIO.getUseCache(),
                ImageIO.getCacheDirectory());
        if (inStream == null)
            throw new IllegalArgumentException("Unable to create an inputstream for the granuleurl:"
                    + (granuleUrl != null ? granuleUrl : "null"));

        // get a reader and try to cache the relevant SPI
        if (cachedReaderSPI == null) {
            reader = ImageIOExt.getImageioReader(inStream);
            if (reader != null)
                cachedReaderSPI = reader.getOriginatingProvider();
        } else
            reader = cachedReaderSPI.createReaderInstance();
        if (reader == null)
            throw new IllegalArgumentException(
                    "Unable to get an ImageReader for the provided file " + granuleUrl.toString());
        final boolean ignoreMetadata = customizeReaderInitialization(reader, null);
        reader.setInput(inStream, false, ignoreMetadata);

        // call internal method which will close everything
        return getLevel(index, reader);

    } catch (IllegalStateException e) {

        // clean up
        try {
            if (inStream != null)
                inStream.close();
        } catch (Throwable ee) {

        } finally {
            if (reader != null)
                reader.dispose();
        }

        throw new IllegalArgumentException(e);

    } catch (IOException e) {

        // clean up
        try {
            if (inStream != null)
                inStream.close();
        } catch (Throwable ee) {
        } finally {
            if (reader != null)
                reader.dispose();
        }

        throw new IllegalArgumentException(e);
    }
}