Example usage for javax.swing ImageIcon getIconWidth

List of usage examples for javax.swing ImageIcon getIconWidth

Introduction

In this page you can find the example usage for javax.swing ImageIcon getIconWidth.

Prototype

public int getIconWidth() 

Source Link

Document

Gets the width of the icon.

Usage

From source file:edu.ku.brc.specify.tasks.subpane.wb.ImageFrame.java

protected void showImage() {
    if (row == null) {
        return;/*from  ww  w.  ja v a2  s  . c  o  m*/
    }

    Set<WorkbenchRowImage> rowImages = row.getWorkbenchRowImages();
    if (rowImages == null || rowImages.size() == 0) {
        noImagesLinked();
        return;
    }

    // adjust the imageIndex to be within the proper bounds (in order to avoid a few error possibilities)
    if (imageIndex < 0) {
        imageIndex = 0;
        tray.setSelectedIndex(imageIndex);
    } else if (imageIndex > rowImages.size() - 1) {
        imageIndex = rowImages.size() - 1;
        tray.setSelectedIndex(imageIndex);
    }

    // try to get the appropriate WorkbenchRowImage
    WorkbenchRowImage rowImage = row.getRowImage(imageIndex);
    if (rowImage == null) {
        // What do we do here?
        // This should never happen.
        // There were images available, but none of them had the right index.
        // Just give the first one, I guess.
        rowImage = rowImages.iterator().next();
        imageIndex = 0;
        tray.setSelectedIndex(imageIndex);
        statusBar.setWarningMessage("Unable to locate an image with the proper index.  Showing first image."); // XXX i18n
    }

    // at this point, we know at least one image is available

    // update the title and status bar
    String fullFilePath = rowImage.getCardImageFullPath();
    String filename = FilenameUtils.getName(fullFilePath);
    setTitle(String.format(getResourceString("WB_IMAGE_X_OF_Y"), imageIndex + 1, rowImages.size())
            + ((filename != null) ? ": " + filename : ""));
    setStatusBarText(fullFilePath);

    ImageIcon image = null;

    Integer lastDisplayedSize = rowToImageSizeHash.get(row.hashCode());
    if (lastDisplayedSize == null || lastDisplayedSize == REDUCED_SIZE) {
        image = rowImage.getReducedImage();
        reduceMI.setSelected(true);
    } else {
        image = rowImage.getFullSizeImage();
        origMI.setSelected(true);
    }

    cardImageLabel.setIcon(image);

    if (image == null) // no image available
    {
        statusBar.setErrorMessage("Unable to load image"); // XXX i18n
    } else // we've got an image
    {
        // this method is simpler than tracking what we're showing and changing to the correct view
        mainPane.remove(noRowSelectedMessagePanel);
        mainPane.remove(noCardImageMessagePanel);
        mainPane.remove(cardImageLabel);
        mainPane.add(cardImageLabel);

        int w = image.getIconWidth();
        int h = image.getIconHeight();
        cardImageLabel.setText(null);
        cardImageLabel.setSize(w, h);
        mainPane.setSize(w, h);
        mainPane.setPreferredSize(new Dimension(w, h));
        enableMenus(true);

        mainPane.validate();
        mainPane.repaint();
    }
}

From source file:edu.ku.brc.specify.Specify.java

/**
 * @param imgEncoded uuencoded image string
 *//*ww  w .  ja  v  a  2s  .  c  o m*/
protected void setAppIcon(final String imgEncoded) {
    String appIconName = getIconName();
    String innerAppIconName = "InnerAppIcon";

    ImageIcon appImgIcon = null;
    if (StringUtils.isNotEmpty(imgEncoded)) {
        appImgIcon = GraphicsUtils.uudecodeImage("", imgEncoded); //$NON-NLS-1$
        if (appImgIcon != null && appImgIcon.getIconWidth() == 32 && appImgIcon.getIconHeight() == 32) {
            appIcon.setIcon(appImgIcon);
            CustomDialog.setAppIcon(appImgIcon);
            CustomFrame.setAppIcon(appImgIcon);
            IconManager.register(innerAppIconName, appImgIcon, null, IconManager.IconSize.Std32);
            return;
        }
    }
    appImgIcon = IconManager.getImage(appIconName, IconManager.IconSize.Std32); //$NON-NLS-1$
    appIcon.setIcon(appImgIcon);
    if (!UIHelper.isMacOS()) {
        ImageIcon otherAppIcon = IconManager.getImage(getOpaqueIconName(), IconManager.IconSize.Std32); //$NON-NLS-1$
        if (otherAppIcon != null) {
            appImgIcon = otherAppIcon;
        }
    }

    CustomDialog.setAppIcon(appImgIcon);
    CustomFrame.setAppIcon(appImgIcon);
    IconManager.register(innerAppIconName, appImgIcon, null, IconManager.IconSize.Std32);

    this.topFrame.setIconImage(appImgIcon.getImage());
}

From source file:net.sf.dvstar.transmission.TransmissionView.java

private void setAdditionalButtons() {
    ResizableIcon ri = new ArrowResizableIcon(9, SwingConstants.SOUTH);
    JCommandButton dropDownButton = new JCommandButton("Text Button", ri);

    ImageIcon imco = globalResourceMap.getImageIcon("btExit.icon");
    Dimension idim = new Dimension(imco.getIconWidth(), imco.getIconHeight());
    idim = new Dimension(40, 40);
    Image im = imco.getImage();//w  w  w. ja v a  2  s .c  o  m

    ImageWrapperResizableIcon iwri = ImageWrapperResizableIcon.getIcon(im, idim);

    JCommandButton taskbarButtonPaste = new JCommandButton("", iwri);

    taskbarButtonPaste.setHorizontalAlignment(SwingConstants.LEFT);
    taskbarButtonPaste.setCommandButtonKind(CommandButtonKind.ACTION_AND_POPUP_MAIN_POPUP);
    //taskbarButtonPaste.setPopupOrientationKind(CommandButtonPopupOrientationKind.DOWNWARD);
    taskbarButtonPaste.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
    taskbarButtonPaste.setDisplayState(TILE_36); // !!!!
    //taskbarButtonPaste.setPreferredSize(new Dimension(80, 48));
    System.out.println("Pref " + taskbarButtonPaste.getPreferredSize());
    System.out.println("Maxi " + taskbarButtonPaste.getMaximumSize());
    System.out.println("Mini " + taskbarButtonPaste.getMinimumSize());
    System.out.println("Size " + taskbarButtonPaste.getSize());
    Dimension d = new Dimension(taskbarButtonPaste.getPreferredSize().width, 48);
    taskbarButtonPaste.setMaximumSize(d);

    taskbarButtonPaste.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Taskbar Paste activated");
        }
    });
    taskbarButtonPaste.setPopupCallback(new PopupPanelCallback() {

        @Override
        public JPopupPanel getPopupPanel(JCommandButton commandButton) {
            return new SamplePopupMenu();
        }
    });

    taskbarButtonPaste.setActionRichTooltip(new RichTooltip("Paste", "Paste the contents of the Clipboard"));
    taskbarButtonPaste.setPopupRichTooltip(new RichTooltip("Paste",
            "Click here for more options such as pasting only the values or formatting"));
    taskbarButtonPaste.setActionKeyTip("1");

    //maiToolBar.add( rb );

    /*
    JRibbonBand rb = new JRibbonBand("", new EmptyResizableIcon(1));
    rb.addCommandButton(dropDownButton, RibbonElementPriority.MEDIUM);
     *
    JButton dropDownButton = DropDownButtonFactory.createDropDownButton(
    resourceMap.getIcon("btConnect.icon"),
    popup);
     */
    //dropDownButton.setBorder(javax.swing.BorderFactory.createEmptyBorder(2,2,2,2));
    //dropDownButton.setBorderPainted( false );

    //btConnect = taskbarButtonPaste;
    maiToolBar.add(taskbarButtonPaste);

}

From source file:nl.softwaredesign.exporter.ODTExportFormat.java

/**
 * {@inheritDoc}//from  ww  w .  ja  v a 2  s . c  o  m
 */
@Override
public void writeImage(ImageIcon image, boolean scaleToPage) throws DocumentExportException {
    if (scaleToPage) {
        logger.debug("Add image " + image);
    } else {
        logger.debug("Add scaled image " + image);
    }
    try {
        if (currentParagraph == null) {
            newParagraph(0, Alignment.CENTER, null, 0.0f, 0.0f, LineSpacing.SINGLE);
        }
        // Again, we have to do this by hand. Go ODF toolkit :(
        OdfFileDom odfFileDom = (OdfFileDom) currentParagraph.getOdfElement().getOwnerDocument();
        OdfDrawFrame frame = odfFileDom.newOdfElement(OdfDrawFrame.class);

        int imgWidth = 0;
        int imgHeight = 0;
        if (scaleToPage) {
            frame.setTextAnchorTypeAttribute("paragraph");
            int pgWidth = (int) currentSectionStyle.getPageSize().getWidthPoints(72.0f);
            int pgHeight = (int) currentSectionStyle.getPageSize().getHeightPoints(72.0f);
            if (currentSectionStyle.getOrientation() == Orientation.LANDSCAPE
                    || currentSectionStyle.getOrientation() == Orientation.REVERSE_LANDSCAPE) {
                // Landscape, switch width and height
                int tmp = pgWidth;
                pgWidth = pgHeight;
                pgHeight = tmp;
            }
            Dimension page = new Dimension(pgWidth, pgHeight);
            Insets margins = new Insets((int) (currentSectionStyle.getMarginTop()),
                    (int) (currentSectionStyle.getMarginLeft()), (int) (currentSectionStyle.getMarginBottom()),
                    (int) (currentSectionStyle.getMarginRight()));
            Dimension pic = new Dimension(image.getIconWidth(), image.getIconHeight());
            // TODO Correct scaling???
        } else {
            frame.setTextAnchorTypeAttribute("as-char");
            imgWidth = image.getIconWidth();
            imgHeight = image.getIconHeight();
        }

        frame.setSvgWidthAttribute("" + DistanceUnit.IN.fromPoints(imgWidth) + "in");
        frame.setSvgHeightAttribute("" + DistanceUnit.IN.fromPoints(imgHeight) + "in");

        OdfDrawImage imageElement = (OdfDrawImage) frame.newDrawImageElement();
        byte[] bytes = imageToBytes(image, "png", Color.white, imgWidth, imgHeight);
        imageCounter++;
        imageElement.newImage(new ByteArrayInputStream(bytes), "Pictures/image" + imageCounter + ".png",
                "image/png");

        currentParagraph.getOdfElement().appendChild(frame);

    } catch (Exception e) {
        throw new DocumentExportException("Could not write image", e);
    }
}

From source file:org.apache.cocoon.reading.ImageReader.java

protected void processStream(InputStream inputStream) throws IOException, ProcessingException {
    if (hasTransform()) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("image " + ((width == 0) ? "?" : Integer.toString(width)) + "x"
                    + ((height == 0) ? "?" : Integer.toString(height)) + " expires: " + expires);
        }/*  w w w.  ja v  a  2s  .  c o m*/

        /*
         * NOTE (SM):
         * Due to Bug Id 4502892 (which is found in *all* JVM implementations from
         * 1.2.x and 1.3.x on all OS!), we must buffer the JPEG generation to avoid
         * that connection resetting by the peer (user pressing the stop button,
         * for example) crashes the entire JVM (yes, dude, the bug is *that* nasty
         * since it happens in JPEG routines which are native!)
         * I'm perfectly aware of the huge memory problems that this causes (almost
         * doubling memory consuption for each image and making the GC work twice
         * as hard) but it's *far* better than restarting the JVM every 2 minutes
         * (since this is the average experience for image-intensive web application
         * such as an image gallery).
         * Please, go to the <a href="http://developer.java.sun.com/developer/bugParade/bugs/4502892.html">Sun Developers Connection</a>
         * and vote this BUG as the one you would like fixed sooner rather than
         * later and all this hack will automagically go away.
         * Many deep thanks to Michael Hartle <mhartle@hartle-klug.com> for tracking
         * this down and suggesting the workaround.
         *
         * UPDATE (SM):
         * This appears to be fixed on JDK 1.4
         */

        try {
            byte content[] = readFully(inputStream);
            ImageIcon icon = new ImageIcon(content);
            BufferedImage original = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),
                    BufferedImage.TYPE_INT_RGB);
            BufferedImage currentImage = original;
            currentImage.getGraphics().drawImage(icon.getImage(), 0, 0, null);

            if (width > 0 || height > 0) {
                double ow = icon.getImage().getWidth(null);
                double oh = icon.getImage().getHeight(null);

                if (usePercent) {
                    if (width > 0) {
                        width = Math.round((int) (ow * width) / 100);
                    }
                    if (height > 0) {
                        height = Math.round((int) (oh * height) / 100);
                    }
                }

                AffineTransformOp filter = new AffineTransformOp(getTransform(ow, oh, width, height),
                        AffineTransformOp.TYPE_BILINEAR);
                WritableRaster scaledRaster = filter.createCompatibleDestRaster(currentImage.getRaster());

                filter.filter(currentImage.getRaster(), scaledRaster);

                currentImage = new BufferedImage(original.getColorModel(), scaledRaster, true, null);
            }

            if (null != grayscaleFilter) {
                grayscaleFilter.filter(currentImage, currentImage);
            }

            if (null != colorFilter) {
                colorFilter.filter(currentImage, currentImage);
            }

            // JVM Bug handling
            if (JVMBugFixed) {
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                JPEGEncodeParam p = encoder.getDefaultJPEGEncodeParam(currentImage);
                p.setQuality(this.quality[0], true);
                encoder.setJPEGEncodeParam(p);
                encoder.encode(currentImage);
            } else {
                ByteArrayOutputStream bstream = new ByteArrayOutputStream();
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bstream);
                JPEGEncodeParam p = encoder.getDefaultJPEGEncodeParam(currentImage);
                p.setQuality(this.quality[0], true);
                encoder.setJPEGEncodeParam(p);
                encoder.encode(currentImage);
                out.write(bstream.toByteArray());
            }

            out.flush();
        } catch (ImageFormatException e) {
            throw new ProcessingException(
                    "Error reading the image. " + "Note that only JPEG images are currently supported.");
        } finally {
            // Bugzilla Bug 25069, close inputStream in finally block
            // this will close inputStream even if processStream throws
            // an exception
            inputStream.close();
        }
    } else {
        // only read the resource - no modifications requested
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("passing original resource");
        }
        super.processStream(inputStream);
    }
}

From source file:org.apache.cocoon.reading.RepoImageReader.java

/**
 * @return the time the read source was last modified or 0 if it is not
 *         possible to detect//from  ww  w.j a v  a 2s . c om
 */
/*
public long getLastModified() {
if (hasRanges()) {
    // This is a byte range request so we can't use the cache, return null.
    return 0;
}
        
if (quickTest) {
    return inputSource.getLastModified();
}
        
final String systemId = (String) documents.get(request.getRequestURI());
// Note: getURI() might be null in some incomplete implementations
final String sourceURI = inputSource.getURI();
if (systemId == null || (sourceURI != null && sourceURI.equals(systemId))) {
    return inputSource.getLastModified();
}
        
documents.remove(request.getRequestURI());
return 0;
}*/

protected void processStream(InputStream inputStream) throws IOException, ProcessingException {

    if (inputStream != null) {
        if (hasTransform()) {
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("image " + ((width == 0) ? "?" : Integer.toString(width)) + "x"
                        + ((height == 0) ? "?" : Integer.toString(height)) + " expires: " + expires);
            }

            try {
                byte content[] = readFully(inputStream);
                ImageIcon icon = new ImageIcon(content);
                BufferedImage original = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),
                        BufferedImage.TYPE_INT_RGB);
                BufferedImage currentImage = original;
                currentImage.getGraphics().drawImage(icon.getImage(), 0, 0, null);

                if (width > 0 || height > 0) {
                    double ow = icon.getImage().getWidth(null);
                    double oh = icon.getImage().getHeight(null);

                    if (usePercent) {
                        if (width > 0) {
                            width = Math.round((int) (ow * width) / 100);
                        }
                        if (height > 0) {
                            height = Math.round((int) (oh * height) / 100);
                        }
                    }

                    AffineTransformOp filter = new AffineTransformOp(getTransform(ow, oh, width, height),
                            AffineTransformOp.TYPE_BILINEAR);
                    WritableRaster scaledRaster = filter.createCompatibleDestRaster(currentImage.getRaster());

                    filter.filter(currentImage.getRaster(), scaledRaster);

                    currentImage = new BufferedImage(original.getColorModel(), scaledRaster, true, null);
                }

                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                JPEGEncodeParam p = encoder.getDefaultJPEGEncodeParam(currentImage);
                p.setQuality(this.quality[0], true);
                encoder.setJPEGEncodeParam(p);
                encoder.encode(currentImage);

                out.flush();
            } catch (ImageFormatException e) {
                throw new ProcessingException(
                        "Error reading the image. " + "Note that only JPEG images are currently supported.");
            } finally {
                // Bugzilla Bug 25069, close inputStream in finally block
                // this will close inputStream even if processStream throws
                // an exception
                inputStream.close();
            }
        } else {
            try {
                InputStream is = inputStream;

                long expires = parameters.getParameterAsInteger("expires", -1);
                if (expires > 0) {
                    response.setDateHeader("Expires", System.currentTimeMillis() + expires);
                }
                response.setHeader("Accept-Ranges", "bytes");

                byte[] buffer = new byte[8192];
                int length;
                while ((length = is.read(buffer)) > -1) {
                    out.write(buffer, 0, length);
                }
                is.close();
                out.flush();
            } catch (RuntimeException e) {
                throw e;
            } finally {
                // Bugzilla Bug 25069, close inputStream in finally block
                // this will close inputStream even if processStream throws
                // an exception
                inputStream.close();
            }

        }
    } else {
        throw new IOException("Deals: Problem, resource not found or Repository not working correctly");
    }

}

From source file:org.craftercms.cstudio.alfresco.dm.content.pipeline.impl.CheckImageSizeProcessor.java

/**
 * check the width and the height of the given image as an inputstream match the width and the height specified
 *
 * @param in/*from  w ww.  j a  v a  2s  . c o m*/
 * @param allowedWidth
 * @param allowedHeight
 * @param lessSize
 * @param assetInfo
 * @return
 * @throws org.craftercms.cstudio.alfresco.service.exception.ServiceException
 * @throws org.craftercms.cstudio.alfresco.service.exception.ContentNotAllowedException
 */
protected InputStream checkForImageSize(InputStream in, int allowedWidth, int allowedHeight, boolean lessSize,
        ContentAssetInfoTO assetInfo) throws ContentNotAllowedException, ContentProcessException {
    ByteArrayOutputStream byteOutput = null;
    try {
        byteOutput = new ByteArrayOutputStream();
        byte[] buffer = new byte[CStudioWebScriptConstants.READ_BUFFER_LENGTH];
        int read = 0;
        while ((read = in.read(buffer)) > 0) {
            byteOutput.write(buffer, 0, read);
        }
        byte[] imageData = byteOutput.toByteArray();
        Image image = Toolkit.getDefaultToolkit().createImage(imageData);
        ImageIcon icon = new ImageIcon(image);
        int height = icon.getIconHeight();
        int width = icon.getIconWidth();
        validateImageSize(allowedWidth, allowedHeight, height, width, lessSize);
        assetInfo.setHeight(height);
        assetInfo.setWidth(width);
        return new ByteArrayInputStream(imageData);
    } catch (IOException e) {
        throw new ContentProcessException(e);
    } finally {
        // close the original inputstream
        ContentUtils.release(in);
        ContentUtils.release(byteOutput);
    }
}

From source file:org.craftercms.studio.impl.v1.content.pipeline.CheckImageSizeProcessor.java

/**
 * check the width and the height of the given image as an inputstream match the width and the height specified
 *
 * @param in//www. ja v  a2s.c  o m
 * @param allowedWidth
 * @param allowedHeight
 * @param lessSize
 * @param assetInfo
 * @return
 */
protected InputStream checkForImageSize(InputStream in, int allowedWidth, int allowedHeight, boolean lessSize,
        ContentAssetInfoTO assetInfo) throws ContentNotAllowedException, ContentProcessException {
    ByteArrayOutputStream byteOutput = null;
    try {
        byteOutput = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];//PORT CStudioWebScriptConstants.READ_BUFFER_LENGTH];
        int read = 0;
        while ((read = in.read(buffer)) > 0) {
            byteOutput.write(buffer, 0, read);
        }
        byte[] imageData = byteOutput.toByteArray();
        Image image = Toolkit.getDefaultToolkit().createImage(imageData);
        ImageIcon icon = new ImageIcon(image);
        int height = icon.getIconHeight();
        int width = icon.getIconWidth();
        validateImageSize(allowedWidth, allowedHeight, height, width, lessSize);
        assetInfo.setHeight(height);
        assetInfo.setWidth(width);
        return new ByteArrayInputStream(imageData);
    } catch (IOException e) {
        throw new ContentProcessException(e);
    } finally {
        // close the original inputstream
        ContentUtils.release(in);
        ContentUtils.release(byteOutput);
    }
}

From source file:org.giavacms.base.controller.ResourceController.java

protected void setDimensions() {
    width = 0;//from   ww  w . j av  a2  s.com
    height = 0;
    croppedImage = null;
    if (!ResourceType.IMAGE.equals(getElement().getResourceType())) {
        return;
    }
    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();
    String folder = servletContext.getRealPath("") + File.separator;
    getElement().setBytes(FileUtils.getBytesFromFile(
            new File(new File(folder, ResourceType.IMAGE.getFolder()), getElement().getName())));
    ImageIcon imageIcon = new ImageIcon(getElement().getBytes());
    width = imageIcon.getIconWidth();
    height = imageIcon.getIconHeight();
}

From source file:org.jajuk.ui.views.CoverView.java

/**
 * Long action to compute image to display (download, resizing...)
 * //from   w w w.j  a v a 2 s.co m
 * @param index 
 * 
 * @throws JajukException the jajuk exception
 */
private void prepareDisplay(final int index) throws JajukException {
    // find next correct cover
    Cover cover = null;
    ImageIcon icon = null;
    try {
        cover = alCovers.get(index); // take image at the given index
        Log.debug("Display cover: " + cover + " at index :" + index);
        Image img = cover.getImage();
        // Never mirror our no cover image
        if (cover.getType().equals(CoverType.NO_COVER)) {
            icon = new ImageIcon(img);
        } else {
            if (
            // should we mirror in our GUI
            (includeControls && Conf.getBoolean(Const.CONF_COVERS_MIRROW_COVER))
                    // should we mirror in fullscreen mode
                    || (!includeControls && Conf.getBoolean(Const.CONF_COVERS_MIRROW_COVER_FS_MODE))) {
                icon = new ImageIcon(UtilGUI.get3dImage(img));
            } else {
                icon = new ImageIcon(img);
            }
        }
        if (icon.getIconHeight() == 0 || icon.getIconWidth() == 0) {
            throw new JajukException(0, "Wrong picture, size is null");
        }
    } catch (final FileNotFoundException e) {
        // do not display a stacktrace for FileNotfound as we expect this in cases
        // where the picture is gone on the net
        Log.warn("Cover image not found at URL: " + (cover == null ? "<null>" : cover.getURL().toString()));
        throw new JajukException(0, e);
    } catch (final UnknownHostException e) {
        // do not display a stacktrace for HostNotFound as we expect this in cases
        // where the whole server is gone on the net
        Log.warn("Cover image not found at URL: " + (cover == null ? "<null>" : cover.getURL().toString()));
        throw new JajukException(0, e);
    } catch (final IOException e) { // this cover cannot be loaded
        Log.error(e);
        throw new JajukException(0, e);
    } catch (final InterruptedException e) { // this cover cannot be loaded
        Log.error(e);
        throw new JajukException(0, e);
    }
    // We apply a 90% of space availability to avoid image cut-offs (see #1283)
    final int iDisplayAreaHeight = (int) (0.9f * CoverView.this.getHeight() - 30);
    final int iDisplayAreaWidth = (int) (0.9f * CoverView.this.getWidth() - 10);
    // check minimum sizes
    if ((iDisplayAreaHeight < 1) || (iDisplayAreaWidth < 1)) {
        return;
    }
    int iNewWidth;
    int iNewHeight;
    if (iDisplayAreaHeight > iDisplayAreaWidth) {
        // Width is smaller than height : try to optimize height
        iNewHeight = iDisplayAreaHeight; // take all possible height
        // we check now if width will be visible entirely with optimized
        // height
        final float fHeightRatio = (float) iNewHeight / icon.getIconHeight();
        if (icon.getIconWidth() * fHeightRatio <= iDisplayAreaWidth) {
            iNewWidth = (int) (icon.getIconWidth() * fHeightRatio);
        } else {
            // no? so we optimize width
            iNewWidth = iDisplayAreaWidth;
            iNewHeight = (int) (icon.getIconHeight() * ((float) iNewWidth / icon.getIconWidth()));
        }
    } else {
        // Height is smaller or equal than width : try to optimize width
        iNewWidth = iDisplayAreaWidth; // take all possible width
        // we check now if height will be visible entirely with
        // optimized width
        final float fWidthRatio = (float) iNewWidth / icon.getIconWidth();
        if (icon.getIconHeight() * fWidthRatio <= iDisplayAreaHeight) {
            iNewHeight = (int) (icon.getIconHeight() * fWidthRatio);
        } else {
            // no? so we optimize width
            iNewHeight = iDisplayAreaHeight;
            iNewWidth = (int) (icon.getIconWidth() * ((float) iNewHeight / icon.getIconHeight()));
        }
    }
    // Note that at this point, the image is fully loaded (done in the ImageIcon constructor)
    ii = UtilGUI.getResizedImage(icon, iNewWidth, iNewHeight);
    // Free memory of source image, removing this causes severe memory leaks ! (tested)
    icon.getImage().flush();
}