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:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java

/**
 * Converts image file into a BufferedImage
 *
 * @param inputFile//from   ww  w.  ja  v a 2s  . co m
 * @return
 * @throws IOException
 */
public static BufferedImage convertImageFileToBI(String inputFile) throws IOException {

    BufferedImage bi = null;

    try {
        ImageIO.setUseCache(false);
        bi = ImageIO.read(new File(inputFile));
    } catch (javax.imageio.IIOException e) // in case tiff format is not recognized, try to resolve exception using ImagePlus (ImageJ) methods
    {
        if (inputFile.endsWith(".tif") || inputFile.endsWith(".tiff")) {
            ImagePlus ip = new ImagePlus(inputFile); // :TODO validate if tiff to be read is truly 16 bit :: otherwise there could be a scaling issue occurring afterwards
            bi = ((ShortProcessor) ip.getProcessor().convertToShort(false)).get16BitBufferedImage();
        } else {
            throw e;
        }
    }

    return bi;
}

From source file:fr.gael.dhus.datastore.processing.impl.ProcessProductImages.java

@Override
public void run(final Product product) {
    if (ImageIO.getUseCache())
        ImageIO.setUseCache(false);

    DrbNode node = null;/* w w  w  . j a v a  2  s. c  o  m*/
    URL url = product.getPath();

    // Prepare the DRb node to be processed
    try {
        // First : force loading the model before accessing items.
        @SuppressWarnings("unused")
        DrbCortexModel model = DrbCortexModel.getDefaultModel();
        node = ProcessingUtils.getNodeFromPath(url.getPath());

        if (node == null) {
            throw new IOException("Cannot Instantiate Drb with URI \"" + url.toExternalForm() + "\".");
        }

    } catch (Exception e) {
        logger.error("Exception raised while processing Quicklook", e);
        return;
    }

    if (!ImageFactory.isImage(node)) {
        logger.debug("No Image.");
        return;
    }

    RenderedImageList input_list = null;
    RenderedImage input_image = null;
    try {
        input_list = ImageFactory.createImage(node);
        input_image = RenderingFactory.createDefaultRendering(input_list);
    } catch (Exception e) {
        logger.debug("Cannot retrieve default rendering");
        if (logger.isDebugEnabled()) {
            logger.debug("Error occurs during rendered image reader", e);
        }

        if (input_list == null)
            return;
        input_image = input_list;
    }

    int quicklook_width = cfgManager.getProductConfiguration().getQuicklookConfiguration().getWidth();
    int quicklook_height = cfgManager.getProductConfiguration().getQuicklookConfiguration().getHeight();
    boolean quicklook_cutting = cfgManager.getProductConfiguration().getQuicklookConfiguration().isCutting();

    logger.info("Generating Quicklook " + quicklook_width + "x" + quicklook_height + " from "
            + input_image.getWidth() + "x" + input_image.getHeight());

    RenderedImage image = ProcessingUtils.ResizeImage(input_image, quicklook_width, quicklook_height, 10f,
            quicklook_cutting);

    String product_id = product.getIdentifier();
    if (product_id == null)
        product_id = "unknown";

    // Manages the quicklook output
    File image_directory = incomingManager.getNewIncomingPath();

    LockFactory lf = new NativeFSLockFactory(image_directory);
    Lock lock = lf.makeLock(".lock-writing");
    try {
        lock.obtain(900000);
    } catch (Exception e) {
        logger.warn("Cannot lock incoming directory - continuing without (" + e.getMessage() + ")");
    }
    File file = new File(image_directory, product_id + "-ql.jpg");
    try {
        ImageIO.write(image, "jpg", file);
        product.setQuicklookPath(file.getPath());
        product.setQuicklookSize(file.length());
    } catch (IOException e) {
        logger.error("Cannot save quicklook.", e);
    }

    // Thumbnail
    int thumbnail_width = cfgManager.getProductConfiguration().getThumbnailConfiguration().getWidth();
    int thumbnail_height = cfgManager.getProductConfiguration().getThumbnailConfiguration().getHeight();
    boolean thumbnail_cutting = cfgManager.getProductConfiguration().getThumbnailConfiguration().isCutting();

    logger.info("Generating Thumbnail " + thumbnail_width + "x" + thumbnail_height + " from "
            + input_image.getWidth() + "x" + input_image.getHeight() + " image.");

    image = ProcessingUtils.ResizeImage(input_image, thumbnail_width, thumbnail_height, 10f, thumbnail_cutting);

    // Manages the quicklook output
    file = new File(image_directory, product_id + "-th.jpg");
    try {
        ImageIO.write(image, "jpg", file);
        product.setThumbnailPath(file.getPath());
        product.setThumbnailSize(file.length());
    } catch (IOException e) {
        logger.error("Cannot save thumbnail.", e);
    }
    SdiImageFactory.close(input_list);
    try {
        lock.close();
    } catch (IOException e) {
    }
}

From source file:net.pms.util.GenericIcons.java

public DLNAThumbnailInputStream getGenericIcon(DLNAResource resource) {
    ImageFormat imageFormat = ImageFormat.JPEG;

    if (resource == null) {
        ImageIO.setUseCache(false);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {//from   ww w .  java 2 s. co m
            ImageIOTools.imageIOWrite(genericUnknownIcon, imageFormat.toString(), out);
            return DLNAThumbnailInputStream.toThumbnailInputStream(out.toByteArray());
        } catch (IOException e) {
            LOGGER.warn("Unexpected error while generating generic thumbnail for null resource: {}",
                    e.getMessage());
            LOGGER.trace("", e);
            return null;
        }
    }

    IconType iconType = IconType.UNKNOWN;
    if (resource.getMedia() != null) {
        if (resource.getMedia().isAudio()) {
            iconType = IconType.AUDIO;
        } else if (resource.getMedia().isImage()) {
            iconType = IconType.IMAGE;
        } else if (resource.getMedia().isVideo()) {
            // FFmpeg parses images as video, try to rectify
            if (resource.getFormat() != null && resource.getFormat().isImage()) {
                iconType = IconType.IMAGE;
            } else {
                iconType = IconType.VIDEO;
            }
        }
    } else if (resource.getFormat() != null) {
        if (resource.getFormat().isAudio()) {
            iconType = IconType.AUDIO;
        } else if (resource.getFormat().isImage()) {
            iconType = IconType.IMAGE;
        } else if (resource.getFormat().isVideo()) {
            iconType = IconType.VIDEO;
        }
    }

    DLNAThumbnail image = null;
    cacheLock.lock();
    try {
        if (!cache.containsKey(imageFormat)) {
            cache.put(imageFormat, new HashMap<IconType, Map<String, DLNAThumbnail>>());
        }
        Map<IconType, Map<String, DLNAThumbnail>> typeCache = cache.get(imageFormat);

        if (!typeCache.containsKey(iconType)) {
            typeCache.put(iconType, new HashMap<String, DLNAThumbnail>());
        }
        Map<String, DLNAThumbnail> imageCache = typeCache.get(iconType);

        String label = getLabelFromImageFormat(resource.getMedia());
        if (label == null) {
            label = getLabelFromFormat(resource.getFormat());
        }
        if (label == null) {
            label = getLabelFromContainer(resource.getMedia());
        }
        if (label != null && label.length() < 5) {
            label = label.toUpperCase(Locale.ROOT);
        } else if (label != null && label.toLowerCase(Locale.ROOT).equals(label)) {
            label = StringUtils.capitalize(label);
        }

        if (imageCache.containsKey(label)) {
            return DLNAThumbnailInputStream.toThumbnailInputStream(imageCache.get(label));
        }

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Creating generic {} thumbnail for {} ({})", iconType.toString().toLowerCase(),
                    label.toUpperCase(), imageFormat);
        }

        try {
            image = addFormatLabelToImage(label, imageFormat, iconType);
        } catch (IOException e) {
            LOGGER.warn("Unexpected error while generating generic thumbnail for \"{}\": {}",
                    resource.getName(), e.getMessage());
            LOGGER.trace("", e);
        }

        imageCache.put(label, image);
    } finally {
        cacheLock.unlock();
    }

    return DLNAThumbnailInputStream.toThumbnailInputStream(image);
}

From source file:eu.dasish.annotation.backend.rest.CachedRepresentationResource.java

/**
 * /*from  www.j a  va  2  s.com*/
 * @param externalId the external UUID of a cached representation.
 * @return the image-blob if the cached-representation's blob is an image file.
 * @throws IOException if logging an error fails (should be changed to sending httpResponse error message).
 */
@GET
@Produces({ "image/jpeg", "image/png" })
@Path("{cachedid: " + BackendConstants.regExpIdentifier + "}/content")
@Transactional(readOnly = true)
public BufferedImage getCachedRepresentationContent(@PathParam("cachedid") String externalId)
        throws IOException {
    Map params = new HashMap();
    try {
        InputStream result = (InputStream) (new RequestWrappers(this)).wrapRequestResource(params,
                new GetCachedRepresentationInputStream(), Resource.CACHED_REPRESENTATION, Access.READ,
                externalId);
        if (result != null) {
            ImageIO.setUseCache(false);
            try {
                BufferedImage retVal = ImageIO.read(result);
                return retVal;
            } catch (IOException e1) {
                loggerServer.info(e1.toString());

                return null;
            }
        } else {
            loggerServer.info(" The cached representation with the id " + externalId + " has null blob.");
            return null;
        }
    } catch (NotInDataBaseException e1) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e1.getMessage());
        return null;
    } catch (ForbiddenException e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage());
        return null;
    }

}

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./*w  w w . j  a v  a2  s  .  c  om*/
 * @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.vns.pdf.impl.PdfDocument.java

private void setWorkingDir() throws IOException {
    ApplicationProperties.KEY.PdfDir.asString();
    workingDir = Paths.get(ApplicationProperties.KEY.PdfDir.asString());
    Files.createDirectories(workingDir, new FileAttribute[0]);
    pdfTempDir = Paths.get(ApplicationProperties.KEY.Workspace.asString(), "temp");
    if (!Files.exists(pdfTempDir, LinkOption.NOFOLLOW_LINKS)) {
        Files.createDirectories(pdfTempDir);
    }//from   ww  w  .  j  a v a 2 s . c om
    ImageIO.setCacheDirectory(pdfTempDir.toFile());
    ImageIO.setUseCache(true);
}

From source file:net.pms.util.GenericIcons.java

/**
 * Add the format(container) name of the media to the generic icon image.
 *
 * @param image BufferdImage to be the label added
 * @param label the media container name to be added as a label
 * @param renderer the renderer configuration
 *
 * @return the generic icon with the container label added and scaled in accordance with renderer setting
 *//*from  w  w  w . j av  a 2s . c o m*/
private DLNAThumbnail addFormatLabelToImage(String label, ImageFormat imageFormat, IconType iconType)
        throws IOException {

    BufferedImage image;
    switch (iconType) {
    case AUDIO:
        image = genericAudioIcon;
        break;
    case IMAGE:
        image = genericImageIcon;
        break;
    case VIDEO:
        image = genericVideoIcon;
        break;
    default:
        image = genericUnknownIcon;
    }

    if (image != null) {
        // Make a copy
        ColorModel colorModel = image.getColorModel();
        image = new BufferedImage(colorModel, image.copyData(null), colorModel.isAlphaPremultiplied(), null);
    }

    ByteArrayOutputStream out = null;

    if (label != null && image != null) {
        out = new ByteArrayOutputStream();
        Graphics2D g = image.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        try {
            int size = 40;
            Font font = new Font(Font.SANS_SERIF, Font.BOLD, size);
            FontMetrics metrics = g.getFontMetrics(font);
            while (size > 7 && metrics.stringWidth(label) > 135) {
                size--;
                font = new Font(Font.SANS_SERIF, Font.BOLD, size);
                metrics = g.getFontMetrics(font);
            }
            // Text center point 127x, 49y - calculate centering coordinates
            int x = 127 - metrics.stringWidth(label) / 2;
            int y = 46 + metrics.getAscent() / 2;
            g.drawImage(image, 0, 0, null);
            g.setColor(Color.WHITE);
            g.setFont(font);
            g.drawString(label, x, y);

            ImageIO.setUseCache(false);
            ImageIOTools.imageIOWrite(image, imageFormat.toString(), out);
        } finally {
            g.dispose();
        }
    }
    return out != null ? DLNAThumbnail.toThumbnail(out.toByteArray(), 0, 0, ScaleType.MAX, imageFormat, false)
            : null;
}

From source file:org.fhcrc.cpl.viewer.quant.gui.QuantitationVisualizer.java

/**
 * Iterate through all fractions, finding and visualizing the selected events
 *///from ww w  . j  ava2 s.c  o  m
public void visualizeQuantEvents() throws IOException {
    //trying to prevent memory leaks
    ImageIO.setUseCache(false);

    if (outHtmlFile == null)
        outHtmlFile = new File(outDir, "quantitation.html");
    if (outTsvFile == null)
        outTsvFile = new File(outDir, "quantitation.tsv");

    _log.debug("visualizeQuantEvents begin, write HTML and text? " + writeHTMLAndText);
    if (writeHTMLAndText) {
        outHtmlPW = new PrintWriter(outHtmlFile);
        outTsvPW = new PrintWriter(new FileOutputStream(outTsvFile, appendTsvOutput));
        _log.debug("opened HTML file " + outHtmlFile.getAbsolutePath() + " and tsv file "
                + outTsvFile.getAbsolutePath() + " for writing.");

        //if we're appending, don't write header.  Cheating by writing it to a fake file
        PrintWriter conditionalTsvPW = outTsvPW;
        if (appendTsvOutput && tsvFileAlreadyExists)
            conditionalTsvPW = new PrintWriter(
                    TempFileManager.createTempFile("fake_file", "fake_file_for_quantvisualizer"));

        QuantEvent.writeHeader(outHtmlPW, conditionalTsvPW, showProteinColumn, show3DPlots);
        _log.debug("Wrote HTML and TSV header");
        TempFileManager.deleteTempFiles("fake_file_for_quantvisualizer");
    }

    boolean processedAFraction = false;
    while (featureSetIterator.hasNext()) {
        FeatureSet fraction = featureSetIterator.next();
        ApplicationContext
                .infoMessage("Evaluating fraction " + MS2ExtraInfoDef.getFeatureSetBaseName(fraction));
        if (fractionsToExamine == null
                || fractionsToExamine.contains(MS2ExtraInfoDef.getFeatureSetBaseName(fraction))) {
            ApplicationContext
                    .infoMessage("Handling fraction " + MS2ExtraInfoDef.getFeatureSetBaseName(fraction));
            handleFraction(fraction);
            processedAFraction = true;
        }
        //trying to prevent memory overflow
        System.gc();
    }
    if (!processedAFraction)
        ApplicationContext.infoMessage("WARNING: no fractions processed");
    if (writeHTMLAndText) {
        QuantEvent.writeFooterAndClose(outHtmlPW, outTsvPW);
        ApplicationContext.infoMessage("Saved HTML file " + outHtmlFile.getAbsolutePath());
        ApplicationContext.infoMessage("Saved TSV file " + outTsvFile.getAbsolutePath());
    }

}

From source file:fr.gael.dhus.datastore.processing.ProcessingManager.java

/**
 * Loads product images from Drb node and stores information inside the
 * product before returning it/*w  ww  . ja v a2 s . c  om*/
 */
private Product extractImages(DrbNode productNode, Product product) {
    if (ImageIO.getUseCache())
        ImageIO.setUseCache(false);

    if (!ImageFactory.isImage(productNode)) {
        LOGGER.debug("No Image.");
        return product;
    }

    RenderedImageList input_list = null;
    RenderedImage input_image = null;
    try {
        input_list = ImageFactory.createImage(productNode);
        input_image = RenderingFactory.createDefaultRendering(input_list);
    } catch (Exception e) {
        LOGGER.debug("Cannot retrieve default rendering");
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Error occurs during rendered image reader", e);
        }

        if (input_list == null) {
            return product;
        }
        input_image = input_list;
    }

    if (input_image == null) {
        return product;
    }

    // Generate Quicklook
    int quicklook_width = cfgManager.getProductConfiguration().getQuicklookConfiguration().getWidth();
    int quicklook_height = cfgManager.getProductConfiguration().getQuicklookConfiguration().getHeight();
    boolean quicklook_cutting = cfgManager.getProductConfiguration().getQuicklookConfiguration().isCutting();

    LOGGER.info("Generating Quicklook " + quicklook_width + "x" + quicklook_height + " from "
            + input_image.getWidth() + "x" + input_image.getHeight());

    RenderedImage image = ProcessingUtils.resizeImage(input_image, quicklook_width, quicklook_height, 10f,
            quicklook_cutting);

    // Manages the quicklook output
    File image_directory = incomingManager.getNewIncomingPath();

    AsyncFileLock afl = null;
    try {
        Path path = Paths.get(image_directory.getAbsolutePath(), ".lock-writing");
        afl = new AsyncFileLock(path);
        afl.obtain(900000);
    } catch (IOException | InterruptedException | TimeoutException e) {
        LOGGER.warn("Cannot lock incoming directory - continuing without (" + e.getMessage() + ")");
    }
    String identifier = product.getIdentifier();
    File file = new File(image_directory, identifier + "-ql.jpg");
    try {
        if (ImageIO.write(image, "jpg", file)) {
            product.setQuicklookPath(file.getPath());
            product.setQuicklookSize(file.length());
        }
    } catch (IOException e) {
        LOGGER.error("Cannot save quicklook.", e);
    }

    // Generate Thumbnail
    int thumbnail_width = cfgManager.getProductConfiguration().getThumbnailConfiguration().getWidth();
    int thumbnail_height = cfgManager.getProductConfiguration().getThumbnailConfiguration().getHeight();
    boolean thumbnail_cutting = cfgManager.getProductConfiguration().getThumbnailConfiguration().isCutting();

    LOGGER.info("Generating Thumbnail " + thumbnail_width + "x" + thumbnail_height + " from "
            + input_image.getWidth() + "x" + input_image.getHeight() + " image.");

    image = ProcessingUtils.resizeImage(input_image, thumbnail_width, thumbnail_height, 10f, thumbnail_cutting);

    // Manages the thumbnail output
    file = new File(image_directory, identifier + "-th.jpg");
    try {
        if (ImageIO.write(image, "jpg", file)) {
            product.setThumbnailPath(file.getPath());
            product.setThumbnailSize(file.length());
        }
    } catch (IOException e) {
        LOGGER.error("Cannot save thumbnail.", e);
    }
    SdiImageFactory.close(input_list);
    if (afl != null) {
        afl.close();
    }
    return product;
}

From source file:com.t3.client.TabletopTool.java

private static void initialize() {
    // First time
    AppSetup.install();//from w  w w  .j a v a  2 s .  c  om

    // Clean up after ourselves
    try {
        FileUtil.delete(AppUtil.getAppHome("tmp"), 2);
    } catch (IOException ioe) {
        TabletopTool.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) {
        TabletopTool.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 T3Frame(menuBar));

    serverCommand = new ServerCommandClientImpl();

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

    try {
        startPersonalServer(CampaignFactory.createBasicCampaign());
    } catch (Exception e) {
        TabletopTool.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();
}