Example usage for java.awt Image getHeight

List of usage examples for java.awt Image getHeight

Introduction

In this page you can find the example usage for java.awt Image getHeight.

Prototype

public abstract int getHeight(ImageObserver observer);

Source Link

Document

Determines the height of the image.

Usage

From source file:org.lnicholls.galleon.util.Tools.java

public static Image getImage(URL url, int width, int height) {
    if (url != null) {
        // System.out.println(url);
        try {/*w ww . jav  a 2  s  . co m*/
            Image internetImage = null;
            if (log.isDebugEnabled())
                log.debug("Downloading internet image=" + url.toExternalForm());

            class TimedThread implements Callable {
                private URL mUrl;

                public TimedThread(URL url) {
                    mUrl = url;
                }

                public synchronized java.lang.Object call() throws java.lang.Exception {
                    return new ImageTracker(mUrl).load();
                }
            }

            TimedCallable timedCallable = new TimedCallable(new TimedThread(url), 2000 * 60);
            internetImage = (Image) timedCallable.call();

            // System.out.println("internetImage="+internetImage);
            if (internetImage == null) {
                log.error("Invalid internet image: " + url.getPath());
            } else {
                // System.out.println("width="+width);
                // System.out.println("height="+height);
                if (width == -1)
                    width = internetImage.getWidth(null);
                if (height == -1)
                    height = internetImage.getHeight(null);

                // System.out.println("width="+width);
                // System.out.println("height="+height);

                Image image = null;
                if (internetImage instanceof BufferedImage) {
                    image = ImageManipulator.getScaledImage((BufferedImage) internetImage, width, height);
                    // System.out.println("image1="+image);
                } else {
                    try {
                        image = createBufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                        Graphics2D graphics2D = ((BufferedImage) image).createGraphics();
                        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                        graphics2D.drawImage(internetImage, 0, 0, width, height, null);
                        graphics2D.dispose();
                        graphics2D = null;
                        // System.out.println("image2="+image);
                    } catch (Throwable ex) {
                        // ex.printStackTrace();
                        image = internetImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
                        // System.out.println("image3="+image);
                    }
                }
                internetImage.flush();
                internetImage = null;

                return image;
            }
        } catch (Throwable ex) {
            // ex.printStackTrace();
            Tools.logException(Tools.class, ex, url.toExternalForm());
        }
    }
    return null;
}

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

/**
 * If we're running on OSX we should call this method to download and
 * install the MapTool logo from the main web site. We cache this image so
 * that it appears correctly if the application is later executed in
 * "offline" mode, so to speak./* w  w  w. j av a 2s.  c  o m*/
 */
private static void macOSXicon() {
    // If we're running on OSX, add the dock icon image
    // -- and change our application name to just "MapTool" (not currently)
    // We wait until after we call initialize() so that the asset and image managers
    // are configured.
    Image img = null;
    File logoFile = new File(AppUtil.getAppHome("config"), "maptool-dock-icon.png");
    URL logoURL = null;
    try {
        logoURL = new URL("http://www.rptools.net/images/logo/RPTools_Map_Logo.png");
    } catch (MalformedURLException e) {
        showError("Attemping to form URL -- shouldn't happen as URL is hard-coded", e);
    }
    try {
        img = ImageUtil.bytesToImage(FileUtils.readFileToByteArray(logoFile));
    } catch (IOException e) {
        log.debug("Attemping to read cached icon: " + logoFile, e);
        try {
            img = ImageUtil.bytesToImage(FileUtil.getBytes(logoURL));
            // If we did download the logo, save it to the 'config' dir for later use.
            BufferedImage bimg = ImageUtil.createCompatibleImage(img, img.getWidth(null), img.getHeight(null),
                    null);
            FileUtils.writeByteArrayToFile(logoFile, ImageUtil.imageToBytes(bimg, "png"));
            img = bimg;
        } catch (IOException e1) {
            log.warn("Cannot read '" + logoURL + "' or  cached '" + logoFile + "'; no dock icon", e1);
        }
    }
    /*
     * Unfortunately the next line doesn't allow Eclipse to compile the code
     * on anything but a Mac. Too bad because there's no problem at runtime
     * since this code wouldn't be executed an any machine *except* a Mac.
     * Sigh.
     * 
     * com.apple.eawt.Application appl =
     * com.apple.eawt.Application.getApplication();
     */
    try {
        Class<?> appClass = Class.forName("com.apple.eawt.Application");
        Method getApplication = appClass.getDeclaredMethod("getApplication", (Class[]) null);
        Object appl = getApplication.invoke(null, (Object[]) null);
        Method setDockIconImage = appl.getClass().getDeclaredMethod("setDockIconImage",
                new Class[] { java.awt.Image.class });
        // If we couldn't grab the image for some reason, don't set the dock bar icon!  Duh!
        if (img != null)
            setDockIconImage.invoke(appl, new Object[] { img });

        if (MapToolUtil.isDebugEnabled()) {
            // For some reason Mac users don't like the dock badge icon.  But from a development standpoint I like seeing the
            // version number in the dock bar.  So we'll only include it when running with MAPTOOL_DEV on the command line.
            Method setDockIconBadge = appl.getClass().getDeclaredMethod("setDockIconBadge",
                    new Class[] { java.lang.String.class });
            String vers = getVersion();
            vers = vers.substring(vers.length() - 2);
            vers = vers.replaceAll("[^0-9]", "0"); // Convert all non-digits to zeroes
            setDockIconBadge.invoke(appl, new Object[] { vers });
        }
    } catch (Exception e) {
        log.info(
                "Cannot find/invoke methods on com.apple.eawt.Application; use -X command line options to set dock bar attributes",
                e);
    }
}

From source file:org.polymap.core.data.image.ImageTransparencyProcessor.java

public static BufferedImage transparency(Image image, final Color markerColor) throws IOException {
    long start = System.currentTimeMillis();

    RGBImageFilter filter = new RGBImageFilter() {
        // the color we are looking for... Alpha bits are set to opaque
        public int markerRGB = markerColor.getRGB() | 0xFF000000;

        byte threshold = 25;

        double range = ((double) 0xFF) / (3 * threshold);

        public final int filterRGB(int x, int y, int rgb) {
            Color probe = new Color(rgb);
            //log.info( "probe=" + probe + ", marker=" + markerColor );

            // delta values
            int dRed = markerColor.getRed() - probe.getRed();
            int dGreen = markerColor.getGreen() - probe.getGreen();
            int dBlue = markerColor.getBlue() - probe.getBlue();
            //log.info( "    dRed=" + dRed + ", dGreen=" + dGreen );

            if (dRed >= 0 && dRed < threshold && dGreen >= 0 && dGreen < threshold && dBlue >= 0
                    && dBlue < threshold) {
                int alpha = (int) Math.round(range * (dRed + dGreen + dBlue));
                //log.info( "    -> alpha=" + alpha );

                return ((alpha << 24) | 0x00FFFFFF) & rgb;
            } else {
                // nothing to do
                return rgb;
            }/*from  w w w  . j  av a 2s  .c  om*/
        }
    };

    //        BufferedImage bimage = null;
    //        if (image instanceof BufferedImage) {
    //            bimage = (BufferedImage)image;
    //        }
    //        else {
    //            bimage = new BufferedImage(
    //                    image.getHeight( null ), image.getWidth( null ), BufferedImage.TYPE_INT_ARGB );
    //            Graphics g = bimage.getGraphics();
    //            g.drawImage( image, 0, 0, null );
    //            g.dispose();
    //        }

    ImageProducer ip = new FilteredImageSource(image.getSource(), filter);
    Image result = Toolkit.getDefaultToolkit().createImage(ip);

    BufferedImage bresult = new BufferedImage(image.getHeight(null), image.getWidth(null),
            BufferedImage.TYPE_INT_ARGB);
    Graphics g = bresult.getGraphics();
    g.drawImage(result, 0, 0, null);
    g.dispose();

    //        // XXX this can surely be done any more clever
    //        int width = bimage.getWidth();
    //        int height = bimage.getHeight();
    //        for (int x=bimage.getMinX(); x<width; x++) {
    //            for (int y=bimage.getMinY(); y<height; y++) {
    //                int filtered = filter.filterRGB( x, y, bimage.getRGB( x, y ) );
    //                result.setRGB( x, y, filtered );
    //            }
    //        }

    log.debug("Transparency done. (" + (System.currentTimeMillis() - start) + "ms)");
    return bresult;
}

From source file:org.muse.mneme.impl.AttachmentServiceImpl.java

/**
 * Create a thumbnail image from the full image in the byte[], of the desired width and height and quality, preserving aspect ratio.
 * //www  . j a  va  2 s.c  o  m
 * @param full
 *        The full image bytes.
 * @param width
 *        The desired max width (pixels).
 * @param height
 *        The desired max height (pixels).
 * @param quality
 *        The JPEG quality (0 - 1).
 * @return The thumbnail JPEG as a byte[].
 * @throws IOException
 * @throws InterruptedException
 */
protected byte[] makeThumb(byte[] full, int width, int height, float quality)
        throws IOException, InterruptedException {
    // read the image from the byte array, waiting till it's processed
    Image fullImage = Toolkit.getDefaultToolkit().createImage(full);
    MediaTracker tracker = new MediaTracker(new Container());
    tracker.addImage(fullImage, 0);
    tracker.waitForID(0);

    // get the full image dimensions
    int fullWidth = fullImage.getWidth(null);
    int fullHeight = fullImage.getHeight(null);

    // preserve the aspect of the full image, not exceeding the thumb dimensions
    if (fullWidth > fullHeight) {
        // full width will take the full desired width, set the appropriate height
        height = (int) ((((float) width) / ((float) fullWidth)) * ((float) fullHeight));
    } else {
        // full height will take the full desired height, set the appropriate width
        width = (int) ((((float) height) / ((float) fullHeight)) * ((float) fullWidth));
    }

    // draw the scaled thumb
    BufferedImage thumbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2D = thumbImage.createGraphics();
    g2D.drawImage(fullImage, 0, 0, width, height, null);

    // encode as jpeg to a byte array
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    BufferedOutputStream out = new BufferedOutputStream(byteStream);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
    param.setQuality(quality, false);
    encoder.setJPEGEncodeParam(param);
    encoder.encode(thumbImage);
    out.close();
    byte[] thumb = byteStream.toByteArray();

    return thumb;
}

From source file:com.aurel.track.attachment.AttachBL.java

private static BufferedImage toBufferedImage(Image image) {
    if (image instanceof BufferedImage) {
        return (BufferedImage) image;
    }//from w  w  w  .j  a va 2  s. c  o  m

    // This code ensures that all the pixels in the image are loaded
    image = new ImageIcon(image).getImage();

    // Determine if the image has transparent pixels; for this method's
    // implementation, see Determining If an Image Has Transparent Pixels
    boolean hasAlpha = hasAlpha(image);

    // Create a buffered image with a format that's compatible with the screen
    BufferedImage bimage = null;
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    try {
        // Determine the type of transparency of the new buffered image
        int transparency = Transparency.OPAQUE;
        if (hasAlpha) {
            transparency = Transparency.BITMASK;
        }

        // Create the buffered image
        GraphicsDevice gs = ge.getDefaultScreenDevice();
        GraphicsConfiguration gc = gs.getDefaultConfiguration();
        bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
    } catch (HeadlessException e) {
        // The system does not have a screen
    }

    if (bimage == null) {
        // Create a buffered image using the default color model
        int type = BufferedImage.TYPE_INT_RGB;
        if (hasAlpha) {
            type = BufferedImage.TYPE_INT_ARGB;
        }
        bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
    }

    // Copy image to buffered image
    Graphics g = bimage.createGraphics();

    // Paint the image onto the buffered image
    g.drawImage(image, 0, 0, null);
    g.dispose();

    return bimage;
}

From source file:SWTGraphics2D.java

/**
 * Draws an image./*from  w w w . ja va 2s .c  o m*/
 *
 * @param image (<code>null</code> not permitted).
 * @param x  the x-coordinate.
 * @param y  the y-coordinate.
 * @param bgcolor  the background color.
 * @param observer  an image observer.
 *
 * @return A boolean.
 */
public boolean drawImage(Image image, int x, int y, Color bgcolor, ImageObserver observer) {
    if (image == null) {
        throw new IllegalArgumentException("Null 'image' argument.");
    }
    int w = image.getWidth(null);
    int h = image.getHeight(null);
    if (w == -1 || h == -1) {
        return false;
    }
    Paint savedPaint = getPaint();
    fill(new Rectangle2D.Double(x, y, w, h));
    setPaint(savedPaint);
    return drawImage(image, x, y, observer);
}

From source file:SWTGraphics2D.java

/**
 * Draws an image./*w w w .j  av a2  s  . c om*/
 *
 * @param image  the image (<code>null</code> not permitted).
 * @param x  the x-coordinate.
 * @param y  the y-coordinate.
 * @param width  the width.
 * @param height  the height.
 * @param bgcolor  the background colour.
 * @param observer  an image observer.
 *
 * @return A boolean.
 */
public boolean drawImage(Image image, int x, int y, int width, int height, Color bgcolor,
        ImageObserver observer) {
    if (image == null) {
        throw new IllegalArgumentException("Null 'image' argument.");
    }
    int w = image.getWidth(null);
    int h = image.getHeight(null);
    if (w == -1 || h == -1) {
        return false;
    }
    Paint savedPaint = getPaint();
    fill(new Rectangle2D.Double(x, y, w, h));
    setPaint(savedPaint);
    return drawImage(image, x, y, width, height, observer);
}

From source file:org.jfree.experimental.swt.SWTGraphics2D.java

/**
 * Draws an image.//from   www.  j  a  v a 2s . co m
 *
 * @param image (<code>null</code> not permitted).
 * @param x  the x-coordinate.
 * @param y  the y-coordinate.
 * @param bgcolor  the background color.
 * @param observer  an image observer.
 *
 * @return A boolean.
 */
public boolean drawImage(Image image, int x, int y, Color bgcolor, ImageObserver observer) {
    ParamChecks.nullNotPermitted(image, "image");
    int w = image.getWidth(null);
    int h = image.getHeight(null);
    if (w == -1 || h == -1) {
        return false;
    }
    Paint savedPaint = getPaint();
    fill(new Rectangle2D.Double(x, y, w, h));
    setPaint(savedPaint);
    return drawImage(image, x, y, observer);
}

From source file:net.sf.maltcms.chromaui.charts.FastHeatMapPlot.java

private void drawOffscreenImage(Image sourceImage) {
    // image creation
    if (offscreenBuffer == null) {
        offscreenBuffer = createCompatibleVolatileImage(sourceImage.getWidth(null), sourceImage.getHeight(null),
                Transparency.TRANSLUCENT);
    }/*from   w w w .  j  a  v  a 2s.  c o m*/
    do {
        if (offscreenBuffer.validate(getGraphicsConfiguration()) == VolatileImage.IMAGE_INCOMPATIBLE) {
            // old vImg doesn't work with new GraphicsConfig; re-create it
            offscreenBuffer = createCompatibleVolatileImage(sourceImage.getWidth(null),
                    sourceImage.getHeight(null), Transparency.TRANSLUCENT);
        }
        Graphics2D g = offscreenBuffer.createGraphics();
        //
        // miscellaneous rendering commands...
        //
        g.drawImage(sourceImage, 0, 0, null);
        g.dispose();
    } while (offscreenBuffer.contentsLost());
}

From source file:msi.gama.outputs.layers.charts.StandardXYItemRenderer.java

/**
 * Draws the visual representation of a single data item.
 *
 * @param g2/*  ww  w .j a  v a 2 s.  c om*/
 *            the graphics device.
 * @param state
 *            the renderer state.
 * @param dataArea
 *            the area within which the data is being drawn.
 * @param info
 *            collects information about the drawing.
 * @param plot
 *            the plot (can be used to obtain standard color information etc).
 * @param domainAxis
 *            the domain axis.
 * @param rangeAxis
 *            the range axis.
 * @param dataset
 *            the dataset.
 * @param series
 *            the series index (zero-based).
 * @param item
 *            the item index (zero-based).
 * @param crosshairState
 *            crosshair information for the plot (<code>null</code> permitted).
 * @param pass
 *            the pass index.
 */
@Override
public void drawItem(final Graphics2D g2, final XYItemRendererState state, final Rectangle2D dataArea,
        final PlotRenderingInfo info, final XYPlot plot, final ValueAxis domainAxis, final ValueAxis rangeAxis,
        final XYDataset dataset, final int series, final int item, final CrosshairState crosshairState,
        final int pass) {

    boolean itemVisible = getItemVisible(series, item);

    // setup for collecting optional entity info...
    Shape entityArea = null;
    EntityCollection entities = null;
    if (info != null) {
        entities = info.getOwner().getEntityCollection();
    }

    final PlotOrientation orientation = plot.getOrientation();
    final Paint paint = getItemPaint(series, item);
    final Stroke seriesStroke = getItemStroke(series, item);
    g2.setPaint(paint);
    g2.setStroke(seriesStroke);

    // get the data point...
    final double x1 = dataset.getXValue(series, item);
    final double y1 = dataset.getYValue(series, item);
    if (Double.isNaN(x1) || Double.isNaN(y1)) {
        itemVisible = false;
    }

    final RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
    final RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
    final double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
    final double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);

    if (getPlotLines()) {
        if (this.drawSeriesLineAsPath) {
            final State s = (State) state;
            if (s.getSeriesIndex() != series) {
                // we are starting a new series path
                s.seriesPath.reset();
                s.lastPointGood = false;
                s.setSeriesIndex(series);
            }

            // update path to reflect latest point
            if (itemVisible && !Double.isNaN(transX1) && !Double.isNaN(transY1)) {
                float x = (float) transX1;
                float y = (float) transY1;
                if (orientation == PlotOrientation.HORIZONTAL) {
                    x = (float) transY1;
                    y = (float) transX1;
                }
                if (s.isLastPointGood()) {
                    // TODO: check threshold
                    s.seriesPath.lineTo(x, y);
                } else {
                    s.seriesPath.moveTo(x, y);
                }
                s.setLastPointGood(true);
            } else {
                s.setLastPointGood(false);
            }
            if (item == dataset.getItemCount(series) - 1) {
                if (s.seriesIndex == series) {
                    // draw path
                    g2.setStroke(lookupSeriesStroke(series));
                    g2.setPaint(lookupSeriesPaint(series));
                    g2.draw(s.seriesPath);
                }
            }
        }

        else if (item != 0 && itemVisible) {
            // get the previous data point...
            final double x0 = dataset.getXValue(series, item - 1);
            final double y0 = dataset.getYValue(series, item - 1);
            if (!Double.isNaN(x0) && !Double.isNaN(y0)) {
                boolean drawLine = true;
                if (getPlotDiscontinuous()) {
                    // only draw a line if the gap between the current and
                    // previous data point is within the threshold
                    final int numX = dataset.getItemCount(series);
                    final double minX = dataset.getXValue(series, 0);
                    final double maxX = dataset.getXValue(series, numX - 1);
                    if (this.gapThresholdType == UnitType.ABSOLUTE) {
                        drawLine = Math.abs(x1 - x0) <= this.gapThreshold;
                    } else {
                        drawLine = Math.abs(x1 - x0) <= (maxX - minX) / numX * getGapThreshold();
                    }
                }
                if (drawLine) {
                    final double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation);
                    final double transY0 = rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation);

                    // only draw if we have good values
                    if (Double.isNaN(transX0) || Double.isNaN(transY0) || Double.isNaN(transX1)
                            || Double.isNaN(transY1)) {
                        return;
                    }

                    if (orientation == PlotOrientation.HORIZONTAL) {
                        state.workingLine.setLine(transY0, transX0, transY1, transX1);
                    } else if (orientation == PlotOrientation.VERTICAL) {
                        state.workingLine.setLine(transX0, transY0, transX1, transY1);
                    }

                    if (state.workingLine.intersects(dataArea)) {
                        g2.draw(state.workingLine);
                    }
                }
            }
        }
    }

    // we needed to get this far even for invisible items, to ensure that
    // seriesPath updates happened, but now there is nothing more we need
    // to do for non-visible items...
    if (!itemVisible) {
        return;
    }

    if (getBaseShapesVisible()) {

        Shape shape = getItemShape(series, item);
        if (orientation == PlotOrientation.HORIZONTAL) {
            shape = ShapeUtilities.createTranslatedShape(shape, transY1, transX1);
        } else if (orientation == PlotOrientation.VERTICAL) {
            shape = ShapeUtilities.createTranslatedShape(shape, transX1, transY1);
        }
        if (shape.intersects(dataArea)) {
            if (getItemShapeFilled(series, item)) {
                g2.fill(shape);
            } else {
                g2.draw(shape);
            }
        }
        entityArea = shape;

    }

    if (getPlotImages()) {
        final Image image = getImage(plot, series, item, transX1, transY1);
        if (image != null) {
            final Point hotspot = getImageHotspot(plot, series, item, transX1, transY1, image);
            g2.drawImage(image, (int) (transX1 - hotspot.getX()), (int) (transY1 - hotspot.getY()), null);
            entityArea = new Rectangle2D.Double(transX1 - hotspot.getX(), transY1 - hotspot.getY(),
                    image.getWidth(null), image.getHeight(null));
        }

    }

    double xx = transX1;
    double yy = transY1;
    if (orientation == PlotOrientation.HORIZONTAL) {
        xx = transY1;
        yy = transX1;
    }

    // draw the item label if there is one...
    if (isItemLabelVisible(series, item)) {
        drawItemLabel(g2, orientation, dataset, series, item, xx, yy, y1 < 0.0);
    }

    final int domainAxisIndex = plot.getDomainAxisIndex(domainAxis);
    final int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis);
    updateCrosshairValues(crosshairState, x1, y1, domainAxisIndex, rangeAxisIndex, transX1, transY1,
            orientation);

    // add an entity for the item...
    if (entities != null && isPointInRect(dataArea, xx, yy)) {
        addEntity(entities, entityArea, dataset, series, item, xx, yy);
    }

}