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 boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2,
        int sy2, ImageObserver observer);

Source Link

Document

Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface.

Usage

From source file:org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject.java

/**
 * High-quality image scaling.//from www  . ja  v a  2  s.c o  m
 */
private BufferedImage scaleImage(BufferedImage image, int width, int height) {
    BufferedImage image2 = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = image2.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g.drawImage(image, 0, 0, width, height, 0, 0, image.getWidth(), image.getHeight(), null);
    g.dispose();
    return image2;
}

From source file:com.josue.tileset.editor.Editor.java

private BufferedImage getTileImage(int x, int y, BufferedImage tileSetImage) {

    BufferedImage tileImage;// w  w w  . ja va  2  s  .c o m
    Graphics2D tileGraphics;

    float opacity = 1L;
    tileImage = createTileImage();
    tileGraphics = tileImage.createGraphics();
    tileGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));

    tileGraphics.drawImage(tileSetImage, 0, // destiny x1
            0, // destiny y1
            TILE_SIZE, // destiny x2
            TILE_SIZE, // destiny y2
            x * TILE_SIZE, // source x1
            y * TILE_SIZE, // source y1
            x * TILE_SIZE + TILE_SIZE, // source x2
            y * TILE_SIZE + TILE_SIZE, // source y2
            null);

    return tileImage;
}

From source file:org.esa.beam.visat.toolviews.stat.XYImagePlot.java

@Override
public boolean render(Graphics2D g2, Rectangle2D dataArea, int index, PlotRenderingInfo info,
        CrosshairState crosshairState) {
    final boolean foundData = super.render(g2, dataArea, index, info, crosshairState);
    if (image != null) {
        final int dx1 = (int) dataArea.getMinX();
        final int dy1 = (int) dataArea.getMinY();
        final int dx2 = (int) dataArea.getMaxX();
        final int dy2 = (int) dataArea.getMaxY();

        synchronized (imageLock) {
            final Rectangle rectangle = getImageSourceArea();
            final int sx1 = rectangle.x;
            final int sy1 = rectangle.y;
            final int sx2 = sx1 + rectangle.width - 1;
            final int sy2 = sy1 + rectangle.height - 1;
            g2.drawImage(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null);
        }//from  ww w. j  a v a2 s .  c o m
    }
    return foundData;
}

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox.PADESPDFBOXSigner.java

@Override
public Image generateVisibleSignaturePreview(SignParameter parameter, java.security.cert.X509Certificate cert,
        int resolution, OperationStatus status, RequestedSignature requestedSignature) throws PDFASError {
    try {//from  www . java 2s .c  om
        PDFBOXObject pdfObject = (PDFBOXObject) status.getPdfObject();

        PDDocument origDoc = new PDDocument();
        origDoc.addPage(new PDPage(PDPage.PAGE_SIZE_A4));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        origDoc.save(baos);
        baos.close();

        pdfObject.setOriginalDocument(new ByteArrayDataSource(baos.toByteArray()));

        SignatureProfileSettings signatureProfileSettings = TableFactory
                .createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings());

        // create Table describtion
        Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(),
                requestedSignature);

        IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings());

        IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main);

        SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

        String signaturePosString = signatureProfileConfiguration.getDefaultPositioning();
        PositioningInstruction positioningInstruction = null;
        if (signaturePosString != null) {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(signaturePosString), "",
                    origDoc, visualObject, false, false);
        } else {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(), "", origDoc,
                    visualObject, false, false);
        }

        origDoc.close();

        SignaturePositionImpl position = new SignaturePositionImpl();
        position.setX(positioningInstruction.getX());
        position.setY(positioningInstruction.getY());
        position.setPage(positioningInstruction.getPage());
        position.setHeight(visualObject.getHeight());
        position.setWidth(visualObject.getWidth());

        requestedSignature.setSignaturePosition(position);

        PDFAsVisualSignatureProperties properties = new PDFAsVisualSignatureProperties(
                pdfObject.getStatus().getSettings(), pdfObject, (PdfBoxVisualObject) visualObject,
                positioningInstruction, signatureProfileSettings);

        properties.buildSignature();
        PDDocument visualDoc;
        synchronized (PDDocument.class) {
            visualDoc = PDDocument.load(properties.getVisibleSignature());
        }
        // PDPageable pageable = new PDPageable(visualDoc);
        List<PDPage> pages = new ArrayList<PDPage>();
        visualDoc.getDocumentCatalog().getPages().getAllKids(pages);

        PDPage firstPage = pages.get(0);

        float stdRes = 72;
        float targetRes = resolution;
        float factor = targetRes / stdRes;

        BufferedImage outputImage = firstPage.convertToImage(BufferedImage.TYPE_4BYTE_ABGR, (int) targetRes);

        BufferedImage cutOut = new BufferedImage((int) (position.getWidth() * factor),
                (int) (position.getHeight() * factor), BufferedImage.TYPE_4BYTE_ABGR);

        Graphics2D graphics = (Graphics2D) cutOut.getGraphics();

        graphics.drawImage(outputImage, 0, 0, cutOut.getWidth(), cutOut.getHeight(), (int) (1 * factor),
                (int) (outputImage.getHeight() - ((position.getHeight() + 1) * factor)),
                (int) ((1 + position.getWidth()) * factor), (int) (outputImage.getHeight()
                        - ((position.getHeight() + 1) * factor) + (position.getHeight() * factor)),
                null);
        return cutOut;
    } catch (PdfAsException e) {
        logger.warn("PDF-AS  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    } catch (Throwable e) {
        logger.warn("Unexpected Throwable  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    }
}

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox2.PADESPDFBOXSigner.java

@Override
public Image generateVisibleSignaturePreview(SignParameter parameter, java.security.cert.X509Certificate cert,
        int resolution, OperationStatus status, RequestedSignature requestedSignature) throws PDFASError {
    try {//from  www . ja  v  a 2s . c  om
        PDFBOXObject pdfObject = (PDFBOXObject) status.getPdfObject();

        PDDocument origDoc = new PDDocument();
        origDoc.addPage(new PDPage(PDRectangle.A4));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        origDoc.save(baos);
        baos.close();

        pdfObject.setOriginalDocument(new ByteArrayDataSource(baos.toByteArray()));

        SignatureProfileSettings signatureProfileSettings = TableFactory
                .createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings());

        // create Table describtion
        Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(),
                requestedSignature);

        IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings());

        IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main);

        SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

        String signaturePosString = signatureProfileConfiguration.getDefaultPositioning();
        PositioningInstruction positioningInstruction = null;
        if (signaturePosString != null) {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(signaturePosString), "",
                    origDoc, visualObject, pdfObject.getStatus().getSettings());
        } else {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(), "", origDoc,
                    visualObject, pdfObject.getStatus().getSettings());
        }

        origDoc.close();

        SignaturePositionImpl position = new SignaturePositionImpl();
        position.setX(positioningInstruction.getX());
        position.setY(positioningInstruction.getY());
        position.setPage(positioningInstruction.getPage());
        position.setHeight(visualObject.getHeight());
        position.setWidth(visualObject.getWidth());

        requestedSignature.setSignaturePosition(position);

        PDFAsVisualSignatureProperties properties = new PDFAsVisualSignatureProperties(
                pdfObject.getStatus().getSettings(), pdfObject, (PdfBoxVisualObject) visualObject,
                positioningInstruction, signatureProfileSettings);

        properties.buildSignature();
        PDDocument visualDoc;
        synchronized (PDDocument.class) {
            visualDoc = PDDocument.load(properties.getVisibleSignature());
        }
        // PDPageable pageable = new PDPageable(visualDoc);

        PDPage firstPage = visualDoc.getDocumentCatalog().getPages().get(0);

        float stdRes = 72;
        float targetRes = resolution;
        float factor = targetRes / stdRes;

        int targetPageNumber = 0;//TODO: is this always the case
        PDFRenderer pdfRenderer = new PDFRenderer(visualDoc);
        BufferedImage outputImage = pdfRenderer.renderImageWithDPI(targetPageNumber, targetRes, ImageType.ARGB);

        //BufferedImage outputImage = firstPage.convertToImage(BufferedImage.TYPE_4BYTE_ABGR, (int) targetRes);

        BufferedImage cutOut = new BufferedImage((int) (position.getWidth() * factor),
                (int) (position.getHeight() * factor), BufferedImage.TYPE_4BYTE_ABGR);

        Graphics2D graphics = (Graphics2D) cutOut.getGraphics();

        graphics.drawImage(outputImage, 0, 0, cutOut.getWidth(), cutOut.getHeight(), (int) (1 * factor),
                (int) (outputImage.getHeight() - ((position.getHeight() + 1) * factor)),
                (int) ((1 + position.getWidth()) * factor), (int) (outputImage.getHeight()
                        - ((position.getHeight() + 1) * factor) + (position.getHeight() * factor)),
                null);
        return cutOut;
    } catch (PdfAsException e) {
        logger.warn("PDF-AS  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    } catch (Throwable e) {
        logger.warn("Unexpected Throwable  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    }
}

From source file:com.springsecurity.plugin.util.ImageResizer.java

public BufferedImage scale(File icon, int targetWidth, int targetHeight) {
    BufferedImage ret = null;//from  www . j a  v  a  2 s . com
    if (icon.exists()) {
        try {
            BufferedImage img = ImageIO.read(icon);
            ret = img;
            int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB
                    : BufferedImage.TYPE_INT_ARGB;
            BufferedImage scratchImage = null;
            Graphics2D g2 = null;
            int w = img.getWidth();
            int h = img.getHeight();
            int prevW = w;
            int prevH = h;
            do {
                if (w > targetWidth) {
                    w /= 2;
                    w = (w < targetWidth) ? targetWidth : w;
                }
                if (h > targetHeight) {
                    h /= 2;
                    h = (h < targetHeight) ? targetHeight : h;
                }
                if (scratchImage == null) {
                    scratchImage = new BufferedImage(w, h, type);
                    g2 = scratchImage.createGraphics();
                }

                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                g2.drawImage(ret, 0, 0, w, h, 0, 0, prevW, prevH, null);

                prevW = w;
                prevH = h;
                ret = scratchImage;
            } while (w != targetWidth || h != targetHeight);
            if (g2 != null) {
                g2.dispose();
            }
            if (targetWidth != ret.getWidth() || targetHeight != ret.getHeight()) {
                scratchImage = new BufferedImage(targetWidth, targetHeight, type);
                g2 = scratchImage.createGraphics();
                g2.drawImage(ret, 0, 0, null);
                g2.dispose();
                ret = scratchImage;
            }
        } catch (IOException e) {
        }
    }
    return ret;
}

From source file:com.openbravo.pos.util.ThumbNailBuilder.java

private Image createThumbNail(Image img) {
    //            MaskFilter filter = new MaskFilter(Color.WHITE);
    //            ImageProducer prod = new FilteredImageSource(img.getSource(), filter);
    //            img = Toolkit.getDefaultToolkit().createImage(prod);

    int targetw;/*from  ww w. j  ava  2s .  co  m*/
    int targeth;

    double scalex = (double) m_width / (double) img.getWidth(null);
    double scaley = (double) m_height / (double) img.getHeight(null);
    if (scalex < scaley) {
        targetw = m_width;
        targeth = (int) (img.getHeight(null) * scalex);
    } else {
        targetw = (int) (img.getWidth(null) * scaley);
        targeth = (int) m_height;
    }

    int midw = img.getWidth(null);
    int midh = img.getHeight(null);
    BufferedImage midimg = null;
    Graphics2D g2d = null;

    Image previmg = img;
    int prevw = img.getWidth(null);
    int prevh = img.getHeight(null);

    do {
        if (midw > targetw) {
            midw /= 2;
            if (midw < targetw) {
                midw = targetw;
            }
        } else {
            midw = targetw;
        }
        if (midh > targeth) {
            midh /= 2;
            if (midh < targeth) {
                midh = targeth;
            }
        } else {
            midh = targeth;
        }
        if (midimg == null) {
            midimg = new BufferedImage(midw, midh, BufferedImage.TYPE_INT_ARGB);
            g2d = midimg.createGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        }
        g2d.drawImage(previmg, 0, 0, midw, midh, 0, 0, prevw, prevh, null);
        prevw = midw;
        prevh = midh;
        previmg = midimg;
    } while (midw != targetw || midh != targeth);

    g2d.dispose();

    if (m_width != midimg.getWidth() || m_height != midimg.getHeight()) {
        midimg = new BufferedImage(m_width, m_height, BufferedImage.TYPE_INT_ARGB);
        int x = (m_width > targetw) ? (m_width - targetw) / 2 : 0;
        int y = (m_height > targeth) ? (m_height - targeth) / 2 : 0;
        g2d = midimg.createGraphics();
        g2d.drawImage(previmg, x, y, x + targetw, y + targeth, 0, 0, targetw, targeth, null);
        g2d.dispose();
        previmg = midimg;
    }
    return previmg;
}

From source file:de.tor.tribes.ui.panels.MinimapPanel.java

protected BufferedImage getScaledImage(int width, int height) {
    BufferedImage tempImg = ImageUtils.createCompatibleBufferedImage(width, height,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = (Graphics2D) tempImg.getGraphics();
    g2d.setColor(new Color(35, 125, 0));
    g2d.fillRect(0, 0, tempImg.getWidth(null), tempImg.getHeight(null));
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2d.drawImage(mBuffer, 0, 0, width, height, 0, 0, mBuffer.getWidth(), mBuffer.getHeight(), null);
    g2d.dispose();//from w ww  .j  a  v  a 2  s  .co m
    return tempImg;
}

From source file:PictureScaler.java

/**
 * Convenience method that returns a scaled instance of the
 * provided BufferedImage.//  ww  w .  j a  va  2  s. c  om
 * 
 * 
 * @param img the original image to be scaled
 * @param targetWidth the desired width of the scaled instance,
 *    in pixels
 * @param targetHeight the desired height of the scaled instance,
 *    in pixels
 * @param hint one of the rendering hints that corresponds to
 *    RenderingHints.KEY_INTERPOLATION (e.g.
 *    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR,
 *    RenderingHints.VALUE_INTERPOLATION_BILINEAR,
 *    RenderingHints.VALUE_INTERPOLATION_BICUBIC)
 * @param progressiveBilinear if true, this method will use a multi-step
 *    scaling technique that provides higher quality than the usual
 *    one-step technique (only useful in down-scaling cases, where
 *    targetWidth or targetHeight is
 *    smaller than the original dimensions)
 * @return a scaled version of the original BufferedImage
 */
public BufferedImage getFasterScaledInstance(BufferedImage img, int targetWidth, int targetHeight, Object hint,
        boolean progressiveBilinear) {
    int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB
            : BufferedImage.TYPE_INT_ARGB;
    BufferedImage ret = img;
    BufferedImage scratchImage = null;
    Graphics2D g2 = null;
    int w, h;
    int prevW = ret.getWidth();
    int prevH = ret.getHeight();
    boolean isTranslucent = img.getTransparency() != Transparency.OPAQUE;

    if (progressiveBilinear) {
        // Use multi-step technique: start with original size, then
        // scale down in multiple passes with drawImage()
        // until the target size is reached
        w = img.getWidth();
        h = img.getHeight();
    } else {
        // Use one-step technique: scale directly from original
        // size to target size with a single drawImage() call
        w = targetWidth;
        h = targetHeight;
    }

    do {
        if (progressiveBilinear && w > targetWidth) {
            w /= 2;
            if (w < targetWidth) {
                w = targetWidth;
            }
        }

        if (progressiveBilinear && h > targetHeight) {
            h /= 2;
            if (h < targetHeight) {
                h = targetHeight;
            }
        }

        if (scratchImage == null || isTranslucent) {
            // Use a single scratch buffer for all iterations
            // and then copy to the final, correctly-sized image
            // before returning
            scratchImage = new BufferedImage(w, h, type);
            g2 = scratchImage.createGraphics();
        }
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
        g2.drawImage(ret, 0, 0, w, h, 0, 0, prevW, prevH, null);
        prevW = w;
        prevH = h;

        ret = scratchImage;
    } while (w != targetWidth || h != targetHeight);

    if (g2 != null) {
        g2.dispose();
    }

    // If we used a scratch buffer that is larger than our target size,
    // create an image of the right size and copy the results into it
    if (targetWidth != ret.getWidth() || targetHeight != ret.getHeight()) {
        scratchImage = new BufferedImage(targetWidth, targetHeight, type);
        g2 = scratchImage.createGraphics();
        g2.drawImage(ret, 0, 0, null);
        g2.dispose();
        ret = scratchImage;
    }

    return ret;
}

From source file:com.moviejukebox.plugin.DefaultImagePlugin.java

/**
 * Draw an overlay on the image, such as a box cover specific for videosource, container, certification if wanted
 *
 * @param movie/*w  w  w  .  j av a 2s  .  co  m*/
 * @param bi
 * @param offsetY
 * @param offsetX
 * @return
 */
private BufferedImage drawOverlay(Movie movie, BufferedImage bi, int offsetX, int offsetY) {

    String source;
    if (overlaySource.equalsIgnoreCase(VIDEOSOURCE)) {
        source = movie.getVideoSource();
    } else if (overlaySource.equalsIgnoreCase(CERTIFICATION)) {
        source = movie.getCertification();
    } else if (overlaySource.equalsIgnoreCase(CONTAINER)) {
        source = movie.getContainer();
    } else {
        source = DEFAULT;
    }

    // Make sure the source is formatted correctly
    source = source.toLowerCase().trim();

    // Check for a blank or an UNKNOWN source and correct it
    if (StringTools.isNotValidString(source)) {
        source = DEFAULT;
    }

    String overlayFilename = source + "_overlay_" + imageType + ".png";

    try {
        BufferedImage biOverlay = GraphicTools.loadJPEGImage(getResourcesPath() + overlayFilename);

        BufferedImage returnBI = new BufferedImage(biOverlay.getWidth(), biOverlay.getHeight(),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2BI = returnBI.createGraphics();
        g2BI.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        g2BI.drawImage(bi, offsetX, offsetY, offsetX + bi.getWidth(), offsetY + bi.getHeight(), 0, 0,
                bi.getWidth(), bi.getHeight(), null);
        g2BI.drawImage(biOverlay, 0, 0, null);

        g2BI.dispose();

        return returnBI;
    } catch (FileNotFoundException ex) {
        LOG.warn(LOG_FAILED_TO_LOAD, overlayFilename);
    } catch (IOException ex) {
        LOG.warn("Failed drawing overlay to {}. Please check that {} is in the resources directory.",
                movie.getBaseName(), overlayFilename);
    }

    return bi;
}