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.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfGraphics2D.java

public boolean drawPdfImage(final com.lowagie.text.Image image, final Image img, AffineTransform xform,
        final ImageObserver obs) {
    if (img == null) {
        throw new NullPointerException("Image must not be null.");
    }//from w  w  w . j  a  v a 2  s .  c  o  m
    if (image == null) {
        throw new NullPointerException("Image must not be null.");
    }
    if (xform == null) {
        xform = AffineTransform.getTranslateInstance(0, 0);
    }

    xform.translate(0, img.getHeight(obs));
    xform.scale(img.getWidth(obs), img.getHeight(obs));

    final AffineTransform inverse = this.normalizeMatrix();
    final AffineTransform flipper = FLIP_TRANSFORM;
    inverse.concatenate(xform);
    inverse.concatenate(flipper);

    try {
        final double[] mx = new double[6];
        inverse.getMatrix(mx);
        if (currentFillGState != 255) {
            PdfGState gs = fillGState[255];
            if (gs == null) {
                gs = new PdfGState();
                gs.setFillOpacity(1);
                fillGState[255] = gs;
            }
            cb.setGState(gs);
        }

        cb.addImage(image, (float) mx[0], (float) mx[1], (float) mx[2], (float) mx[3], (float) mx[4],
                (float) mx[5]);
    } catch (Exception ex) {
        PdfGraphics2D.logger.error("Failed to draw the image: ", ex);
        // throw new IllegalArgumentException("Failed to draw the image");
    } finally {
        if (currentFillGState != 255) {
            final PdfGState gs = fillGState[currentFillGState];
            cb.setGState(gs);
        }
    }
    return true;
}

From source file:ro.nextreports.engine.exporter.ResultExporter.java

private BufferedImage toBufferedImage(Image src) {
    int w = src.getWidth(null);
    int h = src.getHeight(null);
    int type = BufferedImage.TYPE_INT_RGB;
    BufferedImage dest = new BufferedImage(w, h, type);
    Graphics2D g2 = dest.createGraphics();
    g2.drawImage(src, 0, 0, null);//  w ww .  jav a 2  s  .c om
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.dispose();
    return dest;
}

From source file:org.eclipse.birt.chart.device.svg.SVGGraphics2D.java

public boolean drawImage(Image arg0, int arg1, int arg2, Color arg3, ImageObserver arg4) {
    SVGImage image = (SVGImage) arg0;/*  w  w w . ja v  a2s .c  o  m*/
    image.getUrl();
    Element currentElement = createElement("image"); //$NON-NLS-1$
    currentElement.setAttribute("x", toString(arg1)); //$NON-NLS-1$
    currentElement.setAttribute("y", toString(arg2)); //$NON-NLS-1$
    currentElement.setAttribute("width", Integer.toString(arg0.getWidth(arg4))); //$NON-NLS-1$
    currentElement.setAttribute("height", Integer.toString(arg0.getHeight(arg4))); //$NON-NLS-1$
    currentElement.setAttribute("fill", serializeToString(arg3)); //$NON-NLS-1$
    if (clip != null)
        currentElement.setAttribute("clip-path", "url(#clip" + clip.hashCode() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    appendChild(currentElement);

    return true;
}

From source file:org.eclipse.birt.chart.device.svg.SVGGraphics2D.java

public boolean drawImage(Image arg0, int arg1, int arg2, ImageObserver arg3) {
    SVGImage image = (SVGImage) arg0;/*from www  .  j a  va  2 s  .c  o m*/

    Element currentElement = createElement("image"); //$NON-NLS-1$
    currentElement.setAttribute("xlink:href", image.getUrl()); //$NON-NLS-1$
    currentElement.setAttribute("x", toString(arg1)); //$NON-NLS-1$
    currentElement.setAttribute("y", toString(arg2)); //$NON-NLS-1$
    currentElement.setAttribute("width", Integer.toString(arg0.getWidth(arg3))); //$NON-NLS-1$
    currentElement.setAttribute("height", Integer.toString(arg0.getHeight(arg3))); //$NON-NLS-1$
    if (clip != null)
        currentElement.setAttribute("clip-path", "url(#clip" + clip.hashCode() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    appendChild(currentElement);

    return true;
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.graphics.internal.LogicalPageDrawable.java

/**
 * @param content//from  w  ww  .  j a  va2s. c o  m
 * @param image
 */
protected boolean drawImage(final RenderableReplacedContentBox content, Image image) {
    final StyleSheet layoutContext = content.getStyleSheet();
    final boolean shouldScale = layoutContext.getBooleanStyleProperty(ElementStyleKeys.SCALE);

    final int x = (int) StrictGeomUtility.toExternalValue(content.getX());
    final int y = (int) StrictGeomUtility.toExternalValue(content.getY());
    final int width = (int) StrictGeomUtility.toExternalValue(content.getWidth());
    final int height = (int) StrictGeomUtility.toExternalValue(content.getHeight());

    if (width == 0 || height == 0) {
        LogicalPageDrawable.logger.debug("Error: Image area is empty: " + content);
        return false;
    }

    WaitingImageObserver obs = new WaitingImageObserver(image);
    obs.waitImageLoaded();
    final int imageWidth = image.getWidth(obs);
    final int imageHeight = image.getHeight(obs);
    if (imageWidth < 1 || imageHeight < 1) {
        return false;
    }

    final Rectangle2D.Double drawAreaBounds = new Rectangle2D.Double(x, y, width, height);
    final AffineTransform scaleTransform;

    final Graphics2D g2;
    if (shouldScale == false) {
        double deviceScaleFactor = 1;
        final double devResolution = metaData.getNumericFeatureValue(OutputProcessorFeature.DEVICE_RESOLUTION);
        if (metaData.isFeatureSupported(OutputProcessorFeature.IMAGE_RESOLUTION_MAPPING)) {
            if (devResolution != 72.0 && devResolution > 0) {
                // Need to scale the device to its native resolution before attempting to draw the image..
                deviceScaleFactor = (72.0 / devResolution);
            }
        }

        final int clipWidth = Math.min(width, (int) Math.ceil(deviceScaleFactor * imageWidth));
        final int clipHeight = Math.min(height, (int) Math.ceil(deviceScaleFactor * imageHeight));
        final ElementAlignment horizontalAlignment = (ElementAlignment) layoutContext
                .getStyleProperty(ElementStyleKeys.ALIGNMENT);
        final ElementAlignment verticalAlignment = (ElementAlignment) layoutContext
                .getStyleProperty(ElementStyleKeys.VALIGNMENT);
        final int alignmentX = (int) RenderUtility.computeHorizontalAlignment(horizontalAlignment, width,
                clipWidth);
        final int alignmentY = (int) RenderUtility.computeVerticalAlignment(verticalAlignment, height,
                clipHeight);

        g2 = (Graphics2D) getGraphics().create();
        g2.clip(drawAreaBounds);
        g2.translate(x, y);
        g2.translate(alignmentX, alignmentY);
        g2.clip(new Rectangle2D.Float(0, 0, clipWidth, clipHeight));
        g2.scale(deviceScaleFactor, deviceScaleFactor);

        scaleTransform = null;
    } else {
        g2 = (Graphics2D) getGraphics().create();
        g2.clip(drawAreaBounds);
        g2.translate(x, y);
        g2.clip(new Rectangle2D.Float(0, 0, width, height));

        final double scaleX;
        final double scaleY;

        final boolean keepAspectRatio = layoutContext
                .getBooleanStyleProperty(ElementStyleKeys.KEEP_ASPECT_RATIO);
        if (keepAspectRatio) {
            final double scaleFactor = Math.min(width / (double) imageWidth, height / (double) imageHeight);
            scaleX = scaleFactor;
            scaleY = scaleFactor;
        } else {
            scaleX = width / (double) imageWidth;
            scaleY = height / (double) imageHeight;
        }

        final int clipWidth = (int) (scaleX * imageWidth);
        final int clipHeight = (int) (scaleY * imageHeight);

        final ElementAlignment horizontalAlignment = (ElementAlignment) layoutContext
                .getStyleProperty(ElementStyleKeys.ALIGNMENT);
        final ElementAlignment verticalAlignment = (ElementAlignment) layoutContext
                .getStyleProperty(ElementStyleKeys.VALIGNMENT);
        final int alignmentX = (int) RenderUtility.computeHorizontalAlignment(horizontalAlignment, width,
                clipWidth);
        final int alignmentY = (int) RenderUtility.computeVerticalAlignment(verticalAlignment, height,
                clipHeight);

        g2.translate(alignmentX, alignmentY);

        final Object contentCached = content.getContent().getContentCached();
        if (contentCached instanceof Image) {
            image = (Image) contentCached;
            scaleTransform = null;
        } else if (metaData.isFeatureSupported(OutputProcessorFeature.PREFER_NATIVE_SCALING) == false) {
            image = RenderUtility.scaleImage(image, clipWidth, clipHeight,
                    RenderingHints.VALUE_INTERPOLATION_BICUBIC, true);
            content.getContent().setContentCached(image);
            obs = new WaitingImageObserver(image);
            obs.waitImageLoaded();
            scaleTransform = null;
        } else {
            scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
        }
    }

    while (g2.drawImage(image, scaleTransform, obs) == false) {
        obs.waitImageLoaded();
        if (obs.isError()) {
            LogicalPageDrawable.logger.warn("Error while loading the image during the rendering.");
            break;
        }
    }

    g2.dispose();
    return true;
}

From source file:org.rdv.viz.image.ImageViz.java

/**
 * Print the displayed image. If no image is being displayed, this will method
 * will do nothing./*from   w ww  .  ja  va 2  s.  c  o  m*/
 */
private void printImage() {
    // get the displayed image
    final Image displayedImage = getDisplayedImage();
    if (displayedImage == null) {
        return;
    }

    // setup a print job
    PrinterJob printJob = PrinterJob.getPrinterJob();

    // set the renderer for the image
    printJob.setPrintable(new Printable() {
        public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
            //we only have one page to print
            if (pageIndex != 0) {
                return Printable.NO_SUCH_PAGE;
            }

            Graphics2D g2d = (Graphics2D) g;

            // move to corner of imageable page
            g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

            // get page dimensions
            double pageWidth = pageFormat.getImageableWidth();
            double pageHeight = pageFormat.getImageableHeight();

            // get image dimensions
            int imageWidth = displayedImage.getWidth(null);
            int imageHeight = displayedImage.getHeight(null);

            // get scale factor for image
            double widthScale = pageWidth / imageWidth;
            double heightScale = pageHeight / imageHeight;
            double scale = Math.min(widthScale, heightScale);

            // draw image with width and height scaled to page
            int scaledWidth = (int) (scale * imageWidth);
            int scaledHeight = (int) (scale * imageHeight);
            g2d.drawImage(displayedImage, 0, 0, scaledWidth, scaledHeight, null);

            return Printable.PAGE_EXISTS;
        }

    });

    // set the job name to the channel name (plus jpg extension)
    // this is used as a hint for a file name when printing to file
    String channelName = (String) channels.iterator().next();
    String jobName = channelName.replace("/", " - ");
    if (!jobName.endsWith(".jpg")) {
        jobName += ".jpg";
    }
    printJob.setJobName(jobName);

    // show the print dialog and print if ok clicked
    if (printJob.printDialog()) {
        try {
            printJob.print();
        } catch (PrinterException pe) {
            JOptionPane.showMessageDialog(null, "Failed to print image.", "Print Image Error",
                    JOptionPane.ERROR_MESSAGE);
            pe.printStackTrace();
        }
    }
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfGraphics2D.java

/**
 * @see Graphics#drawImage(Image, int, int, int, int, int, int, int, int, Color, ImageObserver)
 *///from   w ww . j a va 2 s. co  m
@Override
public boolean drawImage(final Image img, final int dx1, final int dy1, final int dx2, final int dy2,
        final int sx1, final int sy1, final int sx2, final int sy2, final Color bgcolor,
        final ImageObserver observer) {
    waitForImage(img);
    final double dwidth = (double) dx2 - dx1;
    final double dheight = (double) dy2 - dy1;
    final double swidth = (double) sx2 - sx1;
    final double sheight = (double) sy2 - sy1;

    // if either width or height is 0, then there is nothing to draw
    if (dwidth == 0 || dheight == 0 || swidth == 0 || sheight == 0) {
        return true;
    }

    final double scalex = dwidth / swidth;
    final double scaley = dheight / sheight;

    final double transx = sx1 * scalex;
    final double transy = sy1 * scaley;
    final AffineTransform tx = AffineTransform.getTranslateInstance(dx1 - transx, dy1 - transy);
    tx.scale(scalex, scaley);

    final BufferedImage mask = new BufferedImage(img.getWidth(observer), img.getHeight(observer),
            BufferedImage.TYPE_BYTE_BINARY);
    final Graphics g = mask.getGraphics();
    g.fillRect(sx1, sy1, (int) swidth, (int) sheight);
    drawImage(img, mask, tx, null, observer);
    g.dispose();
    return true;
}

From source file:org.yccheok.jstock.gui.Utils.java

public static BufferedImage toBufferedImage(Image image) {
    if (image instanceof BufferedImage) {
        return (BufferedImage) image;
    }//from   w  ww .  j  a v  a  2  s  .co 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 e661 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:org.eclipse.birt.chart.device.g2d.G2dRendererBase.java

@Override
public void drawImage(ImageRenderEvent ire) throws ChartException {
    if (iv != null) {
        iv.modifyEvent(ire);//from ww  w .  ja v  a  2  s .  c  o m
    }
    if (ire.getImage() == null || ire.getLocation() == null) {
        return;
    }

    java.awt.Image img = null;

    if (ire.getImage() instanceof EmbeddedImage) {
        try {
            byte[] data = Base64.decodeBase64(((EmbeddedImage) ire.getImage()).getData().getBytes());

            img = createImage(data);
        } catch (Exception ilex) {
            throw new ChartException(ChartDeviceExtensionPlugin.ID, ChartException.RENDERING, ilex);
        }
    } else if (ire.getImage().getSource() != ImageSourceType.FILE
            && ire.getImage().getSource() != ImageSourceType.REPORT) {
        try {
            final String sUrl = ire.getImage().getURL();
            img = (java.awt.Image) _ids.loadImage(SecurityUtil.newURL(sUrl));
        } catch (ChartException ilex) {
            // Ignore the invalid path, and log it only
            logger.log(new ChartException(ChartDeviceExtensionPlugin.ID, ChartException.RENDERING, ilex));
        } catch (MalformedURLException muex) {
            throw new ChartException(ChartDeviceExtensionPlugin.ID, ChartException.RENDERING, muex);
        }
    }

    if (img == null) {
        return;
    }

    Location loc = ire.getLocation();
    Position pos = ire.getPosition();
    if (pos == null) {
        pos = Position.INSIDE_LITERAL;
    }

    ImageObserver io = (ImageObserver) _ids.getObserver();

    final boolean bSizeSet = ire.getWidth() * ire.getHeight() > 0;
    int width = bSizeSet ? ire.getWidth() : img.getWidth(io);
    int height = bSizeSet ? ire.getHeight() : img.getHeight(io);
    int x = (int) loc.getX();
    int y = (int) loc.getY();

    switch (pos.getValue()) {
    case Position.INSIDE:
    case Position.OUTSIDE:
        x -= width / 2;
        y -= height / 2;
        break;
    case Position.LEFT:
        x -= width;
        y -= height / 2;
        break;
    case Position.RIGHT:
        y -= height / 2;
        break;
    case Position.ABOVE:
        x -= width / 2;
        y -= height;
        break;
    case Position.BELOW:
        x -= width / 2;
        break;
    }

    _g2d.drawImage(img, x, y, width, height, io);
}

From source file:bayesGame.ui.transformers.BayesNodeProbabilityToGridTransformer.java

@Override
public Icon transform(BayesNode node) {
    Fraction probability = node.getProbability();
    double cells = probability.percentageValue();

    Image grid;
    Color trueColor = BayesGame.trueColor;
    Color falseColor = BayesGame.falseColor;

    boolean hiddennode = node.hasProperty("hidden");
    boolean targetnode = node.hasProperty("target");

    if (node.hasProperty("misguessed")) {
        trueColor = Color.GRAY;//w  ww . j  a  va2 s.c  o m
        falseColor = Color.BLACK;
    }

    // TODO: indicate target nodes somehow

    if (node.cptName == null) {
        node.cptName = "";
    }

    if (node.cptName.equals("DetIS")) {
        grid = new IsNodePainter().paintPercentage(cells, trueColor, falseColor, rows, columns, squaresize);
    } else if (node.cptName.equals("DetNOT")) {
        grid = new NotNodePainter().paintPercentage(cells, trueColor, falseColor, rows, columns, squaresize);
    } else if (node.cptName.equals("Prior")) {
        grid = PriorPainter.paintPercentage(cells, trueColor, falseColor, rows, columns, squaresize);
    } else if (node.cptName.equals("DetOR")) {
        List<Object> parentTypeList = net.getParents(node.type);
        Fraction parentNode1Probability = net.getProbability(parentTypeList.get(0));
        Fraction parentNode2Probability = net.getProbability(parentTypeList.get(1));
        grid = OrNodePainter.paintPercentage(trueColor, falseColor, (int) (rows * squaresize * 3.5), squaresize,
                node, parentNode1Probability, parentNode2Probability);
    } else if (node.cptName.equals("DetAND")) {
        List<Object> parentTypeList = net.getParents(node.type);
        Fraction parentNode1Probability = net.getProbability(parentTypeList.get(0));
        Fraction parentNode2Probability = net.getProbability(parentTypeList.get(1));
        grid = AndNodePainter.paintPercentage(trueColor, falseColor, (int) (rows * squaresize * 3.5),
                squaresize, node, parentNode1Probability, parentNode2Probability);
    } else if (node.cptName.equals("DetNOTAnd")) {
        grid = DetNOTAnd.paintPercentage(cells, trueColor, falseColor, rows, columns, squaresize, node);
    } else if (node.cptName.equals("Bayes")) {
        List<Object> parentTypeList = net.getParents(node.type);
        Fraction parentNodeProbability = net.getProbability(parentTypeList.get(0));
        grid = BayesPainter.paintPercentage(cells, trueColor, falseColor, rows, columns, squaresize, node,
                parentNodeProbability);
    }

    else {
        grid = GridPainter.paintPercentage(cells, trueColor, falseColor, rows, columns, squaresize);
    }

    if (hiddennode) {
        grid = NodePainter.getBorders((BufferedImage) grid, Color.BLACK);
    } else if (!node.isObserved()) {
        grid = NodePainter.getBorders((BufferedImage) grid, Color.GRAY);
    }

    int x_size = grid.getHeight(null);
    double size_multiplier = 0.7;
    int new_x_size = (int) (x_size * size_multiplier);

    ImageIcon icon = new ImageIcon(grid.getScaledInstance(-1, new_x_size, Image.SCALE_SMOOTH));

    // ImageIcon icon = new ImageIcon(grid);

    return icon;
}