Example usage for java.awt Graphics2D drawImage

List of usage examples for java.awt Graphics2D drawImage

Introduction

In this page you can find the example usage for java.awt Graphics2D drawImage.

Prototype

public abstract void drawImage(BufferedImage img, BufferedImageOp op, int x, int y);

Source Link

Document

Renders a BufferedImage that is filtered with a BufferedImageOp .

Usage

From source file:net.sf.mcf2pdf.mcfelements.util.ImageUtil.java

public static BufferedImage readImage(File imageFile) throws IOException {
    int rotation = getImageRotation(imageFile);
    BufferedImage img = ImageIO.read(imageFile);

    if (rotation == 0) {
        return img;
    }//  www  .j  a  va  2s  .c  om

    boolean swapXY = rotation != 180;

    BufferedImage rotated = new BufferedImage(swapXY ? img.getHeight() : img.getWidth(),
            swapXY ? img.getWidth() : img.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = rotated.createGraphics();
    g2d.translate((rotated.getWidth() - img.getWidth()) / 2, (rotated.getHeight() - img.getHeight()) / 2);
    g2d.rotate(Math.toRadians(rotation), img.getWidth() / 2, img.getHeight() / 2);

    g2d.drawImage(img, 0, 0, null);
    g2d.dispose();

    return rotated;
}

From source file:net.mindengine.galen.utils.GalenUtils.java

public static File makeFullScreenshot(WebDriver driver) throws IOException, InterruptedException {
    // scroll up first
    scrollVerticallyTo(driver, 0);//w ww . jav a  2 s  .c  om
    byte[] bytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
    BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
    int capturedWidth = image.getWidth();
    int capturedHeight = image.getHeight();

    long longScrollHeight = (Long) ((JavascriptExecutor) driver).executeScript(
            "return Math.max(" + "document.body.scrollHeight, document.documentElement.scrollHeight,"
                    + "document.body.offsetHeight, document.documentElement.offsetHeight,"
                    + "document.body.clientHeight, document.documentElement.clientHeight);");

    Double devicePixelRatio = ((Number) ((JavascriptExecutor) driver)
            .executeScript(JS_RETRIEVE_DEVICE_PIXEL_RATIO)).doubleValue();

    int scrollHeight = (int) longScrollHeight;

    File file = File.createTempFile("screenshot", ".png");

    int adaptedCapturedHeight = (int) (((double) capturedHeight) / devicePixelRatio);

    BufferedImage resultingImage;

    if (Math.abs(adaptedCapturedHeight - scrollHeight) > 40) {
        int scrollOffset = adaptedCapturedHeight;

        int times = scrollHeight / adaptedCapturedHeight;
        int leftover = scrollHeight % adaptedCapturedHeight;

        final BufferedImage tiledImage = new BufferedImage(capturedWidth,
                (int) (((double) scrollHeight) * devicePixelRatio), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2dTile = tiledImage.createGraphics();
        g2dTile.drawImage(image, 0, 0, null);

        int scroll = 0;
        for (int i = 0; i < times - 1; i++) {
            scroll += scrollOffset;
            scrollVerticallyTo(driver, scroll);
            BufferedImage nextImage = ImageIO.read(
                    new ByteArrayInputStream(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES)));
            g2dTile.drawImage(nextImage, 0, (i + 1) * capturedHeight, null);
        }
        if (leftover > 0) {
            scroll += scrollOffset;
            scrollVerticallyTo(driver, scroll);
            BufferedImage nextImage = ImageIO.read(
                    new ByteArrayInputStream(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES)));
            BufferedImage lastPart = nextImage.getSubimage(0,
                    nextImage.getHeight() - (int) (((double) leftover) * devicePixelRatio),
                    nextImage.getWidth(), leftover);
            g2dTile.drawImage(lastPart, 0, times * capturedHeight, null);
        }

        scrollVerticallyTo(driver, 0);

        resultingImage = tiledImage;
    } else {
        resultingImage = image;
    }

    if (GalenConfig.getConfig().shouldAutoresizeScreenshots()) {
        resultingImage = GalenUtils.resizeScreenshotIfNeeded(driver, resultingImage);
    }

    ImageIO.write(resultingImage, "png", file);
    return file;
}

From source file:QuestionGUI.java

/**
 * Converts a given Image into a BufferedImage
 *
 * CREDIT//from ww  w  .j  a  v a 2  s  . c om
 * https://code.google.com/p/game-engine-for-java/source/browse/src/com/gej/util/ImageTool.java#31
 *
 * @param img The Image to be converted
 * @return The converted BufferedImage
 */
private static BufferedImage toBufferedImage(Image img) {
    if (img instanceof BufferedImage) {
        return (BufferedImage) img;
    }

    // Create a buffered image with transparency
    BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null),
            BufferedImage.TYPE_INT_ARGB);

    // Draw the image on to the buffered image
    Graphics2D bGr = bimage.createGraphics();
    bGr.drawImage(img, 0, 0, null);
    bGr.dispose();

    // Return the buffered image
    return bimage;
}

From source file:net.sf.mcf2pdf.mcfelements.util.ImageUtil.java

/**
 * Rotates the given buffered image by the given angle, and returns a newly
 * created image, containing the rotated image.
 *
 * @param img Image to rotate./*from   w  w w .  j a  va2 s  .c om*/
 * @param angle Angle, in radians, by which to rotate the image.
 * @param drawOffset Receives the offset which is required to draw the image,
 * relative to the original (0,0) corner, so that the center of the image is
 * still on the same position.
 *
 * @return A newly created image containing the rotated image.
 */
public static BufferedImage rotateImage(BufferedImage img, float angle, Point drawOffset) {
    int w = img.getWidth();
    int h = img.getHeight();

    AffineTransform tf = AffineTransform.getRotateInstance(angle, w / 2.0, h / 2.0);

    // get coordinates for all corners to determine real image size
    Point2D[] ptSrc = new Point2D[4];
    ptSrc[0] = new Point(0, 0);
    ptSrc[1] = new Point(w, 0);
    ptSrc[2] = new Point(w, h);
    ptSrc[3] = new Point(0, h);

    Point2D[] ptTgt = new Point2D[4];
    tf.transform(ptSrc, 0, ptTgt, 0, ptSrc.length);

    Rectangle rc = new Rectangle(0, 0, w, h);

    for (Point2D p : ptTgt) {
        if (p.getX() < rc.x) {
            rc.width += rc.x - p.getX();
            rc.x = (int) p.getX();
        }
        if (p.getY() < rc.y) {
            rc.height += rc.y - p.getY();
            rc.y = (int) p.getY();
        }
        if (p.getX() > rc.x + rc.width)
            rc.width = (int) (p.getX() - rc.x);
        if (p.getY() > rc.y + rc.height)
            rc.height = (int) (p.getY() - rc.y);
    }

    BufferedImage imgTgt = new BufferedImage(rc.width, rc.height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = imgTgt.createGraphics();

    // create a NEW rotation transformation around new center
    tf = AffineTransform.getRotateInstance(angle, rc.getWidth() / 2, rc.getHeight() / 2);
    g2d.setTransform(tf);
    g2d.drawImage(img, -rc.x, -rc.y, null);
    g2d.dispose();

    drawOffset.x += rc.x;
    drawOffset.y += rc.y;

    return imgTgt;
}

From source file:com.galenframework.utils.GalenUtils.java

/**
 * Check the devicePixelRatio and adapts the size of the screenshot as if the ratio was 1.0
 * @param driver//from   w w w.  j  a v a2s  . c  o m
 * @param screenshotImage
 * @return
 */
public static BufferedImage resizeScreenshotIfNeeded(WebDriver driver, BufferedImage screenshotImage) {
    Double devicePixelRatio = ((Number) ((JavascriptExecutor) driver)
            .executeScript(JS_RETRIEVE_DEVICE_PIXEL_RATIO)).doubleValue();

    if (devicePixelRatio > 1.0 && screenshotImage.getWidth() > 0) {
        Long screenSize = (Long) ((JavascriptExecutor) driver).executeScript(
                "return Math.max(" + "document.body.scrollWidth, document.documentElement.scrollWidth,"
                        + "document.body.offsetWidth, document.documentElement.offsetWidth,"
                        + "document.body.clientWidth, document.documentElement.clientWidth);");

        Double estimatedPixelRatio = ((double) screenshotImage.getWidth()) / ((double) screenSize);

        if (estimatedPixelRatio > 1.0) {

            int newWidth = (int) (screenshotImage.getWidth() / estimatedPixelRatio);
            int newHeight = (int) (screenshotImage.getHeight() / estimatedPixelRatio);

            Image tmp = screenshotImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
            BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);

            Graphics2D g2d = scaledImage.createGraphics();
            g2d.drawImage(tmp, 0, 0, null);
            g2d.dispose();

            return scaledImage;
        } else
            return screenshotImage;
    } else
        return screenshotImage;
}

From source file:common.utils.ImageUtils.java

/**
  * resize input image to new dinesions(only smaller) into rez parameter
  * @param image input image for scaling
 * @param rez resulting image. must have required width and height
 * @throws IOException//from www. j ava  2s .com
  */
public static void getScaledImageDimmension(BufferedImage image, BufferedImage rez) throws IOException {
    Graphics2D g2 = rez.createGraphics();
    if (rez.getHeight() > image.getHeight() || rez.getWidth() > image.getWidth()) {
        //rez image is bigger no resize
        g2.drawImage(image, 0, 0, null);
        return;
    }
    //1-st getting first side to resize (width or height)
    double scale_factor;
    if (getScaling(image.getHeight(), rez.getHeight()) > getScaling(image.getWidth(), rez.getWidth())) {
        //resize height
        scale_factor = getScaling(image.getHeight(), rez.getHeight());
        int width = (int) (scale_factor * image.getWidth());
        //cut width
        int x = (rez.getWidth() - width) / 2;
        g2.drawImage(image.getScaledInstance(width, rez.getHeight(), Image.SCALE_SMOOTH), x, 0, null);
        //System.out.println("resizing height: h="+image.getHeight()+"/"+rez.getHeight()+"; x="+x);
    } else {
        //resize width
        scale_factor = getScaling(image.getWidth(), rez.getWidth());
        int height = (int) (scale_factor * image.getHeight());
        //cut height
        int y = (rez.getHeight() - height) / 2;
        g2.drawImage(image.getScaledInstance(rez.getWidth(), height, Image.SCALE_SMOOTH), 0, y, null);
        //System.out.println("resizing width: w="+image.getWidth()+"/"+rez.getWidth()+"; y="+y);
    }
    g2.dispose();
}

From source file:org.apache.fop.visual.BitmapComparator.java

/**
 * Builds a combined image that places a number of images next to each other for
 * manual, visual comparison.//from ww  w  .j av a 2s  .  c om
 * @param images the array of bitmaps
 * @return the combined image
 */
public static BufferedImage buildCompareImage(BufferedImage[] images) {
    BufferedImage cmp = new BufferedImage(images[0].getWidth() * images.length, images[0].getHeight(),
            BufferedImage.TYPE_INT_ARGB);

    Graphics2D g = cmp.createGraphics();
    g.setPaint(Color.white);
    g.fillRect(0, 0, cmp.getWidth(), cmp.getHeight());
    int lastWidth = 0;
    for (int i = 0; i < images.length; i++) {
        if (lastWidth > 0) {
            g.translate(lastWidth, 0);
        }
        if (images[i] != null) {
            g.drawImage(images[i], 0, 0, null);
            lastWidth = images[i].getWidth();
        } else {
            lastWidth = 20; //Maybe add a special placeholder image instead later
        }
    }
    g.dispose();

    return cmp;
}

From source file:com.galenframework.utils.GalenUtils.java

public static File makeFullScreenshot(WebDriver driver) throws IOException, InterruptedException {
    // scroll up first
    scrollVerticallyTo(driver, 0);// w  w  w.  j av a 2s.co m
    byte[] bytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
    BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
    int capturedWidth = image.getWidth();
    int capturedHeight = image.getHeight();

    long longScrollHeight = (Long) ((JavascriptExecutor) driver).executeScript(
            "return Math.max(" + "document.body.scrollHeight, document.documentElement.scrollHeight,"
                    + "document.body.offsetHeight, document.documentElement.offsetHeight,"
                    + "document.body.clientHeight, document.documentElement.clientHeight);");

    Double devicePixelRatio = ((Number) ((JavascriptExecutor) driver)
            .executeScript(JS_RETRIEVE_DEVICE_PIXEL_RATIO)).doubleValue();

    int scrollHeight = (int) longScrollHeight;

    File file = File.createTempFile("screenshot", ".png");

    int adaptedCapturedHeight = (int) (((double) capturedHeight) / devicePixelRatio);

    BufferedImage resultingImage;

    if (Math.abs(adaptedCapturedHeight - scrollHeight) > 40) {
        int scrollOffset = adaptedCapturedHeight;

        int times = scrollHeight / adaptedCapturedHeight;
        int leftover = scrollHeight % adaptedCapturedHeight;

        final BufferedImage tiledImage = new BufferedImage(capturedWidth,
                (int) (((double) scrollHeight) * devicePixelRatio), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2dTile = tiledImage.createGraphics();
        g2dTile.drawImage(image, 0, 0, null);

        int scroll = 0;
        for (int i = 0; i < times - 1; i++) {
            scroll += scrollOffset;
            scrollVerticallyTo(driver, scroll);
            BufferedImage nextImage = ImageIO.read(
                    new ByteArrayInputStream(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES)));
            g2dTile.drawImage(nextImage, 0, (i + 1) * capturedHeight, null);
        }
        if (leftover > 0) {
            scroll += scrollOffset;
            scrollVerticallyTo(driver, scroll);
            BufferedImage nextImage = ImageIO.read(
                    new ByteArrayInputStream(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES)));
            BufferedImage lastPart = nextImage.getSubimage(0,
                    nextImage.getHeight() - (int) (((double) leftover) * devicePixelRatio),
                    nextImage.getWidth(), leftover);
            g2dTile.drawImage(lastPart, 0, times * capturedHeight, null);
        }

        scrollVerticallyTo(driver, 0);

        resultingImage = tiledImage;
    } else {
        resultingImage = image;
    }

    if (GalenConfig.getConfig().shouldAutoresizeScreenshots()) {
        try {
            resultingImage = GalenUtils.resizeScreenshotIfNeeded(driver, resultingImage);
        } catch (Exception ex) {
            LOG.trace("Couldn't resize screenshot", ex);
        }
    }

    ImageIO.write(resultingImage, "png", file);
    return file;
}

From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java

/**
 * Rescales using predefined min,max intensities and converts to 8bit. Works for gray- and rgb color images.
 *
 * @param bi16/*from w  ww.j a  v a2  s  .c o m*/
 * @return
 */
public static BufferedImage convertTo8bit(BufferedImage bi16, int min, int max) {
    BufferedImage bi = null;
    if (bi16.getSampleModel().getNumBands() == 1) {
        bi16 = ImageUtils.scaleIntensities(bi16, new int[] { min }, new int[] { max });
        bi = new BufferedImage(bi16.getWidth(), bi16.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
    } else if (bi16.getSampleModel().getNumBands() == 3) {
        throw new IllegalArgumentException("only grayscale images supported");
    } else {
        throw new IllegalArgumentException(
                "Only images with 1 band (gray-color) or 3 bands (rgb) supported. This image has "
                        + bi16.getSampleModel().getNumBands() + " bands.");
    }
    Graphics2D g2d = bi.createGraphics();
    g2d.drawImage(bi16, 0, 0, null);
    g2d.dispose();
    return bi;
}

From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java

/**
 * Rescales using arbitrary intensities and converts to 8bit. Works for gray- and rgb color images.
 *
 * @param bi16/*w  ww  .  j  a v  a 2s.c  om*/
 * @return
 */
public static BufferedImage convertTo8bit(BufferedImage bi16, double intScalingMin, double intScalignMax) {
    // TODO: use min,max from plate meta data, not image specific
    int[][] minMax = ImageUtils.getMinMaxIntensitiesOfBI(bi16);
    BufferedImage bi = null;
    if (bi16.getSampleModel().getNumBands() == 1) {
        bi16 = ImageUtils.scaleIntensities(bi16, getPercentileIntensity(bi16, intScalingMin),
                getPercentileIntensity(bi16, intScalignMax));
        bi = new BufferedImage(bi16.getWidth(), bi16.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
    } else if (bi16.getSampleModel().getNumBands() == 3) {
        bi16 = ImageUtils.scaleIntensities(bi16, getPercentileIntensity(bi16, intScalingMin),
                getPercentileIntensity(bi16, intScalignMax));
        bi = new BufferedImage(bi16.getWidth(), bi16.getHeight(), BufferedImage.TYPE_INT_RGB);
    } else {
        throw new IllegalArgumentException(
                "Only images with 1 band (gray-color) or 3 bands (rgb) supported. This image has "
                        + bi16.getSampleModel().getNumBands() + " bands.");
    }
    Graphics2D g2d = bi.createGraphics();
    g2d.drawImage(bi16, 0, 0, null);
    g2d.dispose();
    return bi;
}