Example usage for javax.imageio ImageIO setUseCache

List of usage examples for javax.imageio ImageIO setUseCache

Introduction

In this page you can find the example usage for javax.imageio ImageIO setUseCache.

Prototype

public static void setUseCache(boolean useCache) 

Source Link

Document

Sets a flag indicating whether a disk-based cache file should be used when creating ImageInputStream s and ImageOutputStream s.

Usage

From source file:net.rptools.maptool.client.MapTool.java

private static void initialize() {
    // First time
    AppSetup.install();/* w ww  .  j a  v  a  2s .  c o  m*/

    // Clean up after ourselves
    try {
        FileUtil.delete(AppUtil.getAppHome("tmp"), 2);
    } catch (IOException ioe) {
        MapTool.showError("While initializing (cleaning tmpdir)", ioe);
    }
    // We'll manage our own images
    ImageIO.setUseCache(false);

    eventDispatcher = new EventDispatcher();
    registerEvents();

    soundManager = new SoundManager();
    try {
        soundManager.configure(SOUND_PROPERTIES);
        soundManager.registerSoundEvent(SND_INVALID_OPERATION, soundManager.getRegisteredSound("Dink"));
    } catch (IOException ioe) {
        MapTool.showError("While initializing (configuring sound)", ioe);
    }

    assetTransferManager = new AssetTransferManager();
    assetTransferManager.addConsumerListener(new AssetTransferHandler());

    playerList = new ObservableList<Player>();
    messageList = new ObservableList<TextMessage>(Collections.synchronizedList(new ArrayList<TextMessage>()));

    handler = new ClientMethodHandler();

    setClientFrame(new MapToolFrame(menuBar));

    serverCommand = new ServerCommandClientImpl();

    player = new Player("", Player.Role.GM, "");

    try {
        startPersonalServer(CampaignFactory.createBasicCampaign());
    } catch (Exception e) {
        MapTool.showError("While starting personal server", e);
    }
    AppActions.updateActions();

    ToolTipManager.sharedInstance().setInitialDelay(AppPreferences.getToolTipInitialDelay());
    ToolTipManager.sharedInstance().setDismissDelay(AppPreferences.getToolTipDismissDelay());
    ChatAutoSave.changeTimeout(AppPreferences.getChatAutosaveTime());

    // TODO: make this more formal when we switch to mina
    new ServerHeartBeatThread().start();
}

From source file:org.gcaldaemon.core.notifier.GmailNotifierWindow.java

GmailNotifierWindow(String style, String sound) throws Exception {
    super(new Frame());

    // Load background
    int w = 300;//from   w  w w .j  a v a2  s.  c o  m
    int h = 110;
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    InputStream in;
    try {
        if (style.indexOf('.') == -1) {
            in = GmailNotifierWindow.class.getResourceAsStream(style + ".gif");
        } else {
            in = new FileInputStream(style);
        }
    } catch (Exception loadError) {
        log.error(loadError.getMessage(), loadError);
        in = GmailNotifierWindow.class.getResourceAsStream("default.gif");
    }
    ImageIO.setUseCache(false);
    background = ImageIO.read(in);
    in.close();
    Dimension size = toolkit.getScreenSize();
    setBounds((size.width - w) / 2, (size.height - h) / 2, w, h);
    metrics = getFontMetrics(PLAIN);

    // Set colors
    for (;;) {
        if (style.equals("metal")) {
            fromColor = Color.WHITE;
            break;
        }
        if (style.equals("green")) {
            titleColor = Color.GREEN;
            dateColor = new Color(0, 145, 0);
            break;
        }
        if (style.equals("blue")) {
            fromColor = Color.WHITE;
            titleColor = new Color(212, 235, 255);
            dateColor = titleColor;
            break;
        }
        if (style.equals("mail")) {
            titleColor = new Color(139, 128, 118);
            dateColor = titleColor;
            break;
        }
        break;
    }

    // Create offscreen buffer
    buffer = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    offscreen = buffer.getGraphics();

    // Set notification sound
    if (sound == null || sound.equals("beep")) {
        clip = null;
    } else {
        try {
            URL url;
            if (sound.indexOf('.') == -1) {
                url = GmailNotifierWindow.class.getResource(sound + ".wav");
            } else {
                sound = sound.replace(File.separatorChar, '/');
                url = new URL("file", "", sound);
            }
            clip = Applet.newAudioClip(url);
        } catch (Exception soundError) {
            log.warn("Unable to load sound: " + sound, soundError);
            clip = null;
        }
    }

    // Init window
    setAlwaysOnTop(true);
    addMouseListener(this);
    addMouseMotionListener(this);
    validate();
}

From source file:org.geotools.utils.progress.BaseArgumentsManager.java

/**
 * /*from   w  w w .java  2  s . c  o  m*/
 * This method is a utlity method for setting various JAi wide hints we will
 * use here and afterwards.
 * 
 * 
 */
private void setJAIHints() {

    // //
    //
    // JAI cache fine tuning
    //
    // //
    final JAI jaiDef = JAI.getDefaultInstance();
    // setting the tile cache
    final TileCache cache = jaiDef.getTileCache();
    cache.setMemoryCapacity(tileCacheSize * 1024 * 1024);

    // //
    // Imageio caching behaviour in case it is ever needed.
    // //
    ImageIO.setUseCache(useImageIOCache);

}

From source file:org.mitre.createEbts.createEbts.java

public static BufferedImage createImageFromBytes(byte[] imageData) throws IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream(imageData);
    ImageIO.setUseCache(false);
    try {// www  .  java2s.  c o  m
        return ImageIO.read(bais);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

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

private void sendResponse(String lFormat, HttpServletResponse pResponse, BufferedImage lImage, String resExt,
        int pQuality) {
    try {/*  w  w  w.j  av a 2  s .co m*/
        OutputStream out = pResponse.getOutputStream();
        short lOutputFormat = -1;
        if (lFormat == null || lFormat.length() <= 0) // sollte vorher abgefangen werden
            throw new T3dException("No output format specified.");
        if (lFormat.equalsIgnoreCase("image/png"))
            lOutputFormat = sPNGOutput;
        if (lFormat.equalsIgnoreCase("image/jpeg"))
            lOutputFormat = sJPEGOutput;
        if (lFormat.equalsIgnoreCase("image/bmp"))
            lOutputFormat = sBMPOutput;
        if (lOutputFormat <= 0) // sollte vorher abgefangen werden
            throw new T3dException("Unsupported output format \"" + lFormat + "\". ");

        switch (lOutputFormat) {
        case sPNGOutput:
            ImageIO.setUseCache(false); // wichtig!
            pResponse.setContentType("image/png");
            //pResponse.setHeader("Cache-Control", "no-store");
            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);
            }
            // out.flush(); // Flushing besser vermeiden, damit Server die Lnge der Anbtweort bestimmen kann
            break;
        case sJPEGOutput:
            try {
                //ImageIO.setUseCache(false); // wichtig!
                pResponse.setContentType("image/jpeg");
                ImageIO.write(lImage, "jpeg", out);
                //                        JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(out); // JPEG-Encoder instanziieren
                //                        JPEGEncodeParam prm = enc.getDefaultJPEGEncodeParam(lImage);
                //                        prm.setQuality(((float) pQuality) / 100.f, false);
                //                        enc.setJPEGEncodeParam(prm);
                //                        enc.encode(lImage); // Bild als JPEG encoden und an Client senden
            } catch (Exception e) {
                throw new T3dException("Did not finish JPEG image send process. " + e.getMessage(), 104);
            }
            break;
        case sBMPOutput:
            try {
                // Merkwrdig, dass nachstehender Code praktisch das korrekte Resultat liefert... (todo)
                pResponse.setContentType("image/bmp");
                ImageIO.write(lImage, "bmp", out);
                //                        JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(out); // JPEG-Encoder instanziieren
                //                        JPEGEncodeParam prm = enc.getDefaultJPEGEncodeParam(lImage);
                //                        prm.setQuality(1.0f, false); // Qualitt auf 100% setzen
                //                        enc.setJPEGEncodeParam(prm);
                //                        enc.encode(lImage); // Bild als JPG encoden und an Client senden
                //                        ImageIO.write(lImage, "jpg", out); // !
            } catch (Exception e) {
                throw new T3dException("Did not finish BMP image send process. " + e.getMessage(), 105);
            }
            break;
        }
        out.close();
    } catch (IOException e) {
        throw new T3dException("An I/O exception occured. The servlet could not send an image reponse.", 106);
    }
}

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

/**
 * bearbeitet HTTP-Get-Anfragen an das Servlet.<p>
 * @param pRequest HTTP-Anfrage-Objekt/* w w w . j a v  a  2 s  .  co 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.sejda.sambox.pdmodel.graphics.image.JPEGFactory.java

private static BufferedImage readJpeg(Object fileOrStream) throws IOException {
    Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("JPEG");
    ImageReader reader = null;/*from  w w w.ja v a 2  s  .c  o m*/
    while (readers.hasNext()) {
        reader = readers.next();
        if (reader.canReadRaster()) {
            break;
        }
    }
    requireIOCondition(nonNull(reader), "Cannot find an ImageIO reader for JPEG image");

    try (ImageInputStream iis = ImageIO.createImageInputStream(fileOrStream)) {
        reader.setInput(iis);
        ImageIO.setUseCache(false);
        return reader.read(0);
    } finally {
        reader.dispose();
    }
}

From source file:svxconv.SVXConv.java

public static final void main(String[] args) {

    for (int i = 0; i < args.length; i++) {
        System.out.println("   " + args[i]);
    }/*from   ww  w  .ja  v a 2  s  .c  o  m*/
    if (args.length == 0) {
        printf(USAGE_MSG);
        System.exit(6);
    }

    ImageIO.setUseCache(false);
    SVXConv conv = new SVXConv();

    try {
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];

            if (arg.charAt(0) != '-') {
                printf("invalid key:%s\n", arg);
                printf(USAGE_MSG);
                System.exit(6);
            }

            if (arg.equals(VOXELSIZE)) {
                conv.setVoxelSize(Double.parseDouble(args[++i]));
            } else if (arg.equals(INPUT)) {
                conv.setInput(args[++i]);
            } else if (arg.equals(OUTPUT)) {
                conv.setOutput(args[++i]);
            } else if (arg.equals(MESH_ERROR_FACTOR)) {
                conv.setMeshErrorFactor(Double.parseDouble(args[++i]));
            } else if (arg.equals(MESH_MIN_PART_VOLUME)) {
                conv.setMeshMinVolume(Double.parseDouble(args[++i]));
            } else if (arg.equals(MESH_MAX_PARTS_COUNT)) {
                conv.setMeshMaxPartsCount(Integer.parseInt(args[++i]));
            } else if (arg.equals(MAX_TRIANGLES)) {
                conv.setMaxTriangles(Integer.parseInt(args[++i]));
            } else if (arg.equals(THREAD_COUNT)) {
                conv.setThreadCount(Integer.parseInt(args[++i]));
            } else if (arg.equals(MESH_SMOOTHING_WIDTH)) {
                conv.setMeshSmoothingWidth(Double.parseDouble(args[++i]));
            } else {

                System.out.println("Unknown parameter: " + arg);
                printf(USAGE_MSG);
                System.exit(6);
            }
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        printf(USAGE_MSG);
        System.exit(6);
    }

    try {
        conv.execute();
    } catch (IOException ioe) {
        System.out.println("Input file not found.");
        ioe.printStackTrace();
        System.exit(1);
    } catch (OutOfMemoryError oom) {
        System.out.println("Out of memory error.");
        oom.printStackTrace();
        System.exit(102);
    } catch (Exception e) {
        // something unexpected...
        System.out.println("Software crash.");
        e.printStackTrace();
        System.exit(101);
    }
}