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, AffineTransform xform, ImageObserver obs);

Source Link

Document

Renders an image, applying a transform from image space into user space before drawing.

Usage

From source file:org.geomajas.plugin.rasterizing.layer.RasterDirectLayer.java

protected void addImage(Graphics2D graphics, ImageResult imageResult, MapViewport viewport) throws IOException {
    Rectangle screenArea = viewport.getScreenArea();
    ReferencedEnvelope worldBounds = viewport.getBounds();
    // convert map bounds to application bounds
    double printScale = screenArea.getWidth() / worldBounds.getWidth();
    if (tileScale < 0) {
        tileScale = printScale;/*from  w  ww  .j  av  a  2 s.c  o m*/
    }
    Envelope applicationBounds = new Envelope((worldBounds.getMinX()) * printScale,
            (worldBounds.getMaxX()) * printScale, -(worldBounds.getMinY()) * printScale,
            -(worldBounds.getMaxY()) * printScale);
    Bbox imageBounds = imageResult.getRasterImage().getBounds();
    // find transform between image bounds and application bounds
    double tx = (imageBounds.getX() * printScale / tileScale - applicationBounds.getMinX());
    double ty = (imageBounds.getY() * printScale / tileScale - applicationBounds.getMinY());
    BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageResult.getImage()));
    double scaleX = imageBounds.getWidth() / image.getWidth() * printScale / tileScale;
    double scaleY = imageBounds.getHeight() / image.getHeight() * printScale / tileScale;
    AffineTransform transform = new AffineTransform();
    transform.translate(tx, ty);
    transform.scale(scaleX, scaleY);
    if (log.isDebugEnabled()) {
        log.debug("adding image, width=" + image.getWidth() + ",height=" + image.getHeight() + ",x=" + tx
                + ",y=" + ty);
    }
    // opacity
    log.debug("before drawImage");
    // create a copy to apply transform
    Graphics2D g = (Graphics2D) graphics.create();
    // apply opacity to image off-graphics to avoid interference with whatever opacity model is used by graphics
    BufferedImage opaqueCopy = makeOpaque(image);
    g.drawImage(opaqueCopy, transform, null);
    log.debug("after drawImage");
}

From source file:org.hydroponics.dao.JDBCHydroponicsDaoImpl.java

public byte[] getThumbnail(BufferedImage buffImage) throws IOException {
    BufferedImage pDestImage = new BufferedImage(Constants.THUMBNAIL_WIDTH, Constants.THUMBNAIL_HEIGHT,
            BufferedImage.TYPE_3BYTE_BGR);

    AffineTransform transform = new AffineTransform();
    transform.scale((float) Constants.THUMBNAIL_WIDTH / (float) buffImage.getWidth(),
            (float) Constants.THUMBNAIL_HEIGHT / (float) buffImage.getHeight());

    Graphics2D g = (Graphics2D) pDestImage.getGraphics();

    //set the rendering hints for a good thumbnail image
    Map m = g.getRenderingHints();
    m.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    m.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    m.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    m.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g.setRenderingHints(m);/*from w w w . j  a  va2  s .c  o m*/

    g.drawImage(buffImage, transform, null);
    g.dispose();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ImageIO.write(pDestImage, "JPEG", out);
    return out.toByteArray();
}

From source file:PrintCanvas3D.java

public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {

    if (pi >= 1) {
        return Printable.NO_SUCH_PAGE;
    }/*from   ww  w .  j a  v  a  2 s.co m*/

    Graphics2D g2d = (Graphics2D) g;
    //g2d.translate(pf.getImageableX(), pf.getImageableY());
    AffineTransform t2d = new AffineTransform();
    t2d.translate(pf.getImageableX(), pf.getImageableY());
    double xscale = pf.getImageableWidth() / (double) bImage.getWidth();
    double yscale = pf.getImageableHeight() / (double) bImage.getHeight();
    double scale = Math.min(xscale, yscale);
    t2d.scale(scale, scale);
    try {
        g2d.drawImage(bImage, t2d, this);
    } catch (Exception ex) {
        ex.printStackTrace();
        return Printable.NO_SUCH_PAGE;
    }
    return Printable.PAGE_EXISTS;
}

From source file:web.diva.server.model.SomClustering.SomClustImgGenerator.java

private BufferedImage rotateImage(BufferedImage masterImage, int angle) {
    int virtualAngle = getVirtualAngle(angle);
    Dimension size = new Dimension(masterImage.getWidth(), masterImage.getHeight());
    int masterWidth = masterImage.getWidth();
    int masterHeight = masterImage.getHeight();

    double x = 0; //masterWidth / 2.0;
    double y = 0; //masterHeight / 2.0;

    switch (virtualAngle) {
    case 0:/*ww w .  j  ava 2s.c  o  m*/
        break;
    case 180:
        break;
    case 90:
    case 270:
        size = new Dimension(masterImage.getHeight(), masterImage.getWidth());
        x = (masterHeight - masterWidth) / 2.0;
        y = (masterWidth - masterHeight) / 2.0;
        break;
    }
    BufferedImage renderedImage = new BufferedImage(size.width, size.height, masterImage.getTransparency());
    Graphics2D g2d = renderedImage.createGraphics();

    AffineTransform at = AffineTransform.getTranslateInstance(x, y);

    at.rotate(Math.toRadians(virtualAngle), masterWidth / 2.0, masterHeight / 2.0);
    g2d.drawImage(masterImage, at, null);

    g2d.dispose();
    return renderedImage;
}

From source file:net.frontlinesms.plugins.forms.FormsPluginController.java

private void convertByteImageToFile(byte[] imageByte, String path) throws Exception {
    System.out.println("path ...... convertByteImageToFile ......... " + path);

    ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
    Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");

    ImageReader reader = (ImageReader) readers.next();
    Object source = bis;//www  .  j  av  a 2  s  . c o m
    ImageInputStream iis = ImageIO.createImageInputStream(source);
    reader.setInput(iis, true);
    ImageReadParam param = reader.getDefaultReadParam();

    Image image = reader.read(0, param);
    //got an image file

    BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
            BufferedImage.TYPE_INT_RGB);
    //bufferedImage is the RenderedImage to be written

    Graphics2D g2 = bufferedImage.createGraphics();
    g2.drawImage(image, null, null);

    File imageFile = new File(path);
    ImageIO.write(bufferedImage, "jpg", imageFile);
    System.out.println(" end write image ");
}

From source file:AntiAlias.java

/** Draw the example */
public void paint(Graphics g1) {
    Graphics2D g = (Graphics2D) g1;
    BufferedImage image = // Create an off-screen image
            new BufferedImage(65, 35, BufferedImage.TYPE_INT_RGB);
    Graphics2D ig = image.createGraphics(); // Get its Graphics for drawing

    // Set the background to a gradient fill. The varying color of
    // the background helps to demonstrate the anti-aliasing effect
    ig.setPaint(new GradientPaint(0, 0, Color.black, 65, 35, Color.white));
    ig.fillRect(0, 0, 65, 35);// w  ww  . j a v  a 2  s  . c om

    // Set drawing attributes for the foreground.
    // Most importantly, turn on anti-aliasing.
    ig.setStroke(new BasicStroke(2.0f)); // 2-pixel lines
    ig.setFont(new Font("Serif", Font.BOLD, 18)); // 18-point font
    ig.setRenderingHint(RenderingHints.KEY_ANTIALIASING, // Anti-alias!
            RenderingHints.VALUE_ANTIALIAS_ON);

    // Now draw pure blue text and a pure red oval
    ig.setColor(Color.blue);
    ig.drawString("Java", 9, 22);
    ig.setColor(Color.red);
    ig.drawOval(1, 1, 62, 32);

    // Finally, scale the image by a factor of 10 and display it
    // in the window. This will allow us to see the anti-aliased pixels
    g.drawImage(image, AffineTransform.getScaleInstance(10, 10), this);

    // Draw the image one more time at its original size, for comparison
    g.drawImage(image, 0, 0, this);
}

From source file:be.fedict.eidviewer.gui.printing.IDPrintout.java

public int print(Graphics graphics, PageFormat pageFormat, int pageNumber) throws PrinterException {
    // we only support printing all in one single page
    if (pageNumber > 0)
        return Printable.NO_SUCH_PAGE;

    logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
            .append("width", pageFormat.getWidth()).append("height", pageFormat.getHeight())
            .append("imageableWidth", pageFormat.getImageableWidth())
            .append("imageableHeight", pageFormat.getImageableHeight())
            .append("imageableX", pageFormat.getImageableX()).append("imageableY", pageFormat.getImageableY())
            .append("orientation", pageFormat.getOrientation())
            .append("paper.width", pageFormat.getPaper().getWidth())
            .append("paper.height", pageFormat.getPaper().getHeight())
            .append("paper.imageableWidth", pageFormat.getPaper().getImageableWidth())
            .append("paper.imageableHeight", pageFormat.getPaper().getImageableHeight())
            .append("paper.imageableX", pageFormat.getPaper().getImageableX())
            .append("paper.imageableY", pageFormat.getPaper().getImageableY()).toString());

    logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
            .append("clip.width", graphics.getClipBounds().width)
            .append("clip.height", graphics.getClipBounds().height).append("clip.x", graphics.getClipBounds().x)
            .append("clip.y", graphics.getClipBounds().y).toString());

    // translate graphics2D with origin at top left first imageable location
    Graphics2D graphics2D = (Graphics2D) graphics;
    graphics2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

    // keep imageable width and height as variables for clarity (we use them often)
    float imageableWidth = (float) pageFormat.getImageableWidth();
    float imageableHeight = (float) pageFormat.getImageableHeight();

    // Coat of Arms images are stored at approx 36 DPI, scale 1/2 to get to Java default of 72DPI
    AffineTransform coatOfArmsTransform = new AffineTransform();
    coatOfArmsTransform.scale(0.5, 0.5);

    // photo images are stored at approx 36 DPI, scale 1/2 to get to Java default of 72DPI
    AffineTransform photoTransform = new AffineTransform();
    photoTransform.scale(0.5, 0.5);//from  w  w w  .  j a  v a 2  s . c om
    photoTransform.translate((imageableWidth * 2) - (photo.getWidth(this)), 0);

    // make sure foreground is black, and draw coat of Arms and photo at the top of the page
    // using the transforms to scale them to 72DPI.
    graphics2D.setColor(Color.BLACK);
    graphics2D.drawImage(coatOfArms, coatOfArmsTransform, null);
    graphics2D.drawImage(photo, photoTransform, null);

    // calculate some sizes that need to take into account the scaling of the graphics, to avoid dragging
    // those non-intuitive "/2" further along in the code.
    float headerHeight = (float) (coatOfArms.getHeight(this)) / 2;
    float coatOfArmsWidth = (float) (coatOfArms.getWidth(this)) / 2;
    float photoWidth = (float) (photo.getWidth(this)) / 2;
    float headerSpaceBetweenImages = imageableWidth
            - (coatOfArmsWidth + photoWidth + (SPACE_BETWEEN_ITEMS * 2));

    logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("headerHeight", headerHeight)
            .append("coatOfArmsWidth", coatOfArmsWidth).append("photoWidth", photoWidth)
            .append("headerSpaceBetweenImages", headerSpaceBetweenImages).toString());

    // get localised strings for card type. We'll take a new line every time a ";" is found in the resource
    String[] cardTypeStr = (bundle.getString("type_" + this.identity.getDocumentType().toString())
            .toUpperCase()).split(";");

    // if a "mention" is present, append it so it appears below the card type string, between brackets

    if (identity.getSpecialOrganisation() != SpecialOrganisation.UNSPECIFIED) {
        String mention = TextFormatHelper.getSpecialOrganisationString(bundle,
                identity.getSpecialOrganisation());
        if (mention != null && !mention.isEmpty()) {
            String[] cardTypeWithMention = new String[cardTypeStr.length + 1];
            System.arraycopy(cardTypeStr, 0, cardTypeWithMention, 0, cardTypeStr.length);
            cardTypeWithMention[cardTypeStr.length] = "(" + mention + ")";
            cardTypeStr = cardTypeWithMention;
        }
    }

    // iterate from MAXIMAL_FONT_SIZE, calculating how much space would be required to fit the card type strings
    // stop when a font size is found where they all fit the space between the graphics in an orderly manner
    boolean sizeFound = false;
    int fontSize;
    for (fontSize = TITLE_MAXIMAL_FONT_SIZE; (fontSize >= MINIMAL_FONT_SIZE) && (!sizeFound); fontSize--) // count down slowly until we find one that fits nicely
    {
        logger.log(Level.FINE, "fontSize=" + fontSize + " sizeFound=" + sizeFound);
        graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize));
        sizeFound = (ImageUtilities.getTotalStringWidth(graphics2D, cardTypeStr) < headerSpaceBetweenImages)
                && (ImageUtilities.getTotalStringHeight(graphics2D, cardTypeStr) < headerHeight);
    }

    // unless with extremely small papers, a size should always have been found.
    // draw the card type strings, centered, between the images at the top of the page
    if (sizeFound) {
        graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize + 1));
        float cardTypeHeight = cardTypeStr.length * ImageUtilities.getStringHeight(graphics2D);
        float cardTypeBaseLine = ((headerHeight - cardTypeHeight) / 2) + ImageUtilities.getAscent(graphics2D);
        float cardTypeLineHeight = ImageUtilities.getStringHeight(graphics2D);

        logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
                .append("cardTypeHeight", cardTypeHeight).append("cardTypeBaseLine", cardTypeBaseLine)
                .append("cardTypeLineHeight", cardTypeLineHeight).toString());

        for (int i = 0; i < cardTypeStr.length; i++) {
            float left = (coatOfArmsWidth + SPACE_BETWEEN_ITEMS
                    + (headerSpaceBetweenImages - ImageUtilities.getStringWidth(graphics2D, cardTypeStr[i]))
                            / 2);
            float leading = (float) cardTypeLineHeight * i;
            graphics2D.drawString(cardTypeStr[i], left, cardTypeBaseLine + leading);
        }
    }

    // populate idAttributes with all the information from identity and address
    // as well as date printed and some separators
    List<IdentityAttribute> idAttributes = populateAttributeList();

    // draw a horizontal line just below the header (images + card type titles)
    graphics2D.drawLine(0, (int) headerHeight, (int) imageableWidth, (int) headerHeight);

    // calculate how much space is left between the header and the bottom of the imageable area

    headerHeight += 32; // take some distance from header

    float imageableDataHeight = imageableHeight - headerHeight;
    float totalDataWidth = 0, totalDataHeight = 0;
    float labelWidth, widestLabelWidth = 0;
    float valueWidth, widestValueWidth = 0;

    // iterate from MAXIMAL_FONT_SIZE, calculating how much space would be required to fit the information in idAttributes into
    // the space between the header and the bottom of the imageable area
    // stop when a font size is found where it all fits in an orderly manner
    sizeFound = false;
    for (fontSize = MAXIMAL_FONT_SIZE; (fontSize >= MINIMAL_FONT_SIZE) && (!sizeFound); fontSize--) // count down slowly until we find one that fits nicely
    {
        logger.log(Level.FINE, "fontSize=" + fontSize + " sizeFound=" + sizeFound);
        graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize));

        widestLabelWidth = 0;
        widestValueWidth = 0;

        for (IdentityAttribute attribute : idAttributes) {
            if (attribute == SEPARATOR)
                continue;

            labelWidth = ImageUtilities.getStringWidth(graphics2D, attribute.getLabel());
            valueWidth = ImageUtilities.getStringWidth(graphics2D, attribute.getValue());
            if (labelWidth > widestLabelWidth)
                widestLabelWidth = labelWidth;
            if (valueWidth > widestValueWidth)
                widestValueWidth = valueWidth;
        }

        totalDataWidth = widestLabelWidth + SPACE_BETWEEN_ITEMS + widestValueWidth;
        totalDataHeight = ImageUtilities.getStringHeight(graphics2D)
                + (ImageUtilities.getStringHeight(graphics2D) * idAttributes.size());

        if ((totalDataWidth < imageableWidth) && (totalDataHeight < imageableDataHeight))
            sizeFound = true;
    }

    logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
            .append("widestLabelWidth", widestLabelWidth).append("widestValueWidth", widestValueWidth)
            .append("totalDataWidth", totalDataWidth).append("totalDataHeight", totalDataHeight).toString());

    // unless with extremely small papers, a size should always have been found.
    // draw the identity, addess and date printed information, in 2 columns, centered inside the
    // space between the header and the bottom of the imageable area
    if (sizeFound) {
        graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize));
        float labelsLeft = (imageableWidth - totalDataWidth) / 2;
        float valuesLeft = labelsLeft + widestLabelWidth + SPACE_BETWEEN_ITEMS;
        float dataLineHeight = ImageUtilities.getStringHeight(graphics2D);
        float dataTop = dataLineHeight + headerHeight + ((imageableDataHeight - totalDataHeight) / 2);
        float lineNumber = 0;

        logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("labelsLeft", labelsLeft)
                .append("valuesLeft", valuesLeft).append("dataLineHeight", dataLineHeight)
                .append("dataTop", dataTop).toString());

        for (IdentityAttribute attribute : idAttributes) {
            if (attribute != SEPARATOR) // data
            {
                graphics2D.setColor(attribute.isRelevant() ? Color.BLACK : Color.LIGHT_GRAY);
                graphics2D.drawString(attribute.getLabel(), labelsLeft,
                        dataTop + (lineNumber * dataLineHeight));
                graphics2D.drawString(attribute.getValue(), valuesLeft,
                        dataTop + (lineNumber * dataLineHeight));
            } else // separator
            {
                int y = (int) (((dataTop + (lineNumber * dataLineHeight) + (dataLineHeight / 2)))
                        - ImageUtilities.getAscent(graphics2D));
                graphics2D.setColor(Color.BLACK);
                graphics2D.drawLine((int) labelsLeft, y, (int) (labelsLeft + totalDataWidth), y);
            }
            lineNumber++;
        }
    }

    // tell Java printing that all this makes for a page worth printing :-)
    return Printable.PAGE_EXISTS;
}

From source file:net.sf.firemox.clickable.target.card.VirtualCard.java

@SuppressWarnings("null")
@Override/*from w w  w .j av  a 2s.  c om*/
public void paintComponent(Graphics g) {
    final Graphics2D g2D = (Graphics2D) g;

    // Renderer
    g2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    // Optimization card painting
    final MZone container = card.getContainer();
    final boolean shortPaint = container == null || !container.isMustBePainted(card);

    // tap/reverse operation : PI/2, PI, -PI/2 rotation
    if (!shortPaint) {
        if (container.isMustBePaintedReversed(card)) {
            if (card.tapped) {
                g2D.translate(rotateTransformY, CardFactory.cardWidth + rotateTransformX);
                g2D.rotate(angle - Math.PI / 2);
            } else {
                g2D.translate(CardFactory.cardWidth + rotateTransformX,
                        CardFactory.cardHeight + rotateTransformY);
                g2D.rotate(Math.PI - angle);
            }
        } else {
            if (card.tapped) {
                g2D.translate(CardFactory.cardHeight + rotateTransformY, rotateTransformX);
                g2D.rotate(Math.PI / 2 + angle);
            } else {
                g2D.translate(rotateTransformX, rotateTransformY);
                g2D.rotate(angle);
            }
        }
    }

    if (container != null) {
        if (container.isVisibleForOpponent() && !card.isVisibleForOpponent() && card.isVisibleForYou()) {
            /*
             * This card is visible for you but not for opponent in despite of the
             * fact the container is public.
             */
            g2D.drawImage(card.scaledImage(), null, null);
            g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
            g2D.drawImage(DatabaseFactory.scaledBackImage, null, null);
        } else if (!card.isVisibleForYou()) {
            g2D.drawImage(DatabaseFactory.scaledBackImage, null, null);
        } else {
            g2D.drawImage(card.scaledImage(), null, null);
        }
    }

    if (shortPaint)
        return;

    /*
     * The card picture is displayed as a rounded rectangle with 0,90,180 or
     * 270
     */
    if (card.isHighLighted && (card.isVisibleForYou() || StackManager.idHandedPlayer == 0)) {
        // Draw the rounded colored rectangle
        g2D.setColor(card.highLightColor);
        g2D.draw3DRect(0, 0, CardFactory.cardWidth - 2, CardFactory.cardHeight - 2, false);
    }

    // Draw the eventual progress bar
    card.database.updatePaintNotification(card, g);

    // Cursor for our pretty pictures
    int px = 3;
    int py = 3;
    int maxX = CardFactory.cardWidth - 2;

    // for in-play, visible cards
    if (card.isVisibleForYou() || (container != null && container.isVisibleForYou())) {

        // draw registers above the card's picture
        if (refreshToolTipFilter().powerANDtoughness) {
            // power / toughness
            final String powerANDtoughness = String.valueOf(card.getValue(IdTokens.POWER)) + "/"
                    + card.getValue(IdTokens.TOUGHNESS);
            g2D.setFont(g2D.getFont().deriveFont(Font.BOLD, 13));
            final Rectangle2D stringDim = g2D.getFontMetrics().getStringBounds(powerANDtoughness, g2D);
            g2D.setColor(CardFactory.powerToughnessColor);
            g2D.drawString(powerANDtoughness, (int) (CardFactory.cardWidth - stringDim.getWidth() - 3),
                    CardFactory.cardHeight - 5);
            g2D.setColor(Color.BLUE);
            g2D.drawString(powerANDtoughness, (int) (CardFactory.cardWidth - stringDim.getWidth() - 3),
                    CardFactory.cardHeight - 6);
        }

        /*
         * START drawing additional pictures
         */

        // draw state pictures
        for (StatePicture statePicture : CardFactory.statePictures) {
            if (px + 13 > maxX) {
                px = 3;
                py += 13;
            }
            if (statePicture.paint(card, g2D, px, py)) {
                px += 13;
            }
        }

        // draw properties
        if (card.cachedProperties != null) {
            for (Integer property : card.cachedProperties) {
                if (Configuration.getBoolean("card.property.picture", true)
                        && CardFactory.propertyPictures.get(property) != null) {
                    // There is an associated picture to this property
                    if (px + 13 > maxX) {
                        px = 3;
                        py += 13;
                    }
                    g2D.drawImage(CardFactory.propertyPictures.get(property), px, py, 12, 12, null);
                    px += 13;
                }
            }
        }
    }

    // draw attached objects
    int startX = 3;
    int startY = CardFactory.cardHeight - 18;
    if (card.registerModifiers != null) {
        for (int i = card.registerModifiers.length; i-- > 0;) {
            if (card.registerModifiers[i] != null) {
                startX = card.registerModifiers[i].paintObject(g, startX, startY);
            }
        }
    }
    if (card.propertyModifier != null) {
        startX = card.propertyModifier.paintObject(g, startX, startY);
    }
    if (card.idCardModifier != null) {
        card.idCardModifier.paintObject(g, startX, startY);
        /*
         * END drawing additional pictures
         */
    }

    // Draw the target Id if helper said it
    final String id = TargetHelper.getInstance().getMyId(card);
    if (id != null) {
        if (px + 13 > maxX) {
            px = 3;
            py += 13;
        }
        if (id == TargetHelper.STR_CONTEXT1) {
            // TODO I am in the context 1, draw a picture
            g2D.setColor(Color.BLUE);
            g2D.setFont(g2D.getFont().deriveFont(Font.BOLD, 60 / id.length()));
            g2D.drawString(id, 5, CardFactory.cardHeight - 15);
        } else if (id == TargetHelper.STR_CONTEXT2) {
            // TODO I am in the context 2, draw a picture
            g2D.setColor(Color.BLUE);
            g2D.setFont(g2D.getFont().deriveFont(Font.BOLD, 60 / id.length()));
            g2D.drawString(id, 5, CardFactory.cardHeight - 15);
        } else if (id != TargetHelper.STR_SOURCE) {
            // } else if (id == TargetHelper.STR_SOURCE) {
            // TODO I am the source, draw a picture
            // } else {
            // I am a target
            g2D.drawImage(TargetHelper.getInstance().getTargetPictureSml(), px, py, null);
            py += 12;
        }
    }

    g2D.dispose();
}

From source file:org.encuestame.business.images.ImageThumbnailGeneratorImpl.java

/**
 * Create a thumbnail image and save it to disk.
 *
 * This algorithm is based on:/*  www  .ja v a 2s.  co  m*/
 *      http://www.philreeve.com/java_high_quality_thumbnails.php
 *
 * @param imageIn           The image you want to scale.
 * @param fileOut           The output file.
 * @param largestDimension  The largest dimension, so that neither the width nor height
 *                          will exceed this value.
 *
 * @return the image that was created, null if imageIn or fileOut is null.
 * @throws java.io.IOException if something goes wrong when saving as jpeg
 */
public BufferedImage createThumbnailImage(Image imageIn, File fileOut, int largestDimension)
        throws IOException {
    if ((imageIn == null) || (fileOut == null)) {
        return null;
    }
    //it seems to not return the right size until the methods get called for the first time
    imageIn.getWidth(null);
    imageIn.getHeight(null);

    // Find biggest dimension
    int nImageWidth = imageIn.getWidth(null);
    int nImageHeight = imageIn.getHeight(null);
    int nImageLargestDim = Math.max(nImageWidth, nImageHeight);
    double scale = (double) largestDimension / (double) nImageLargestDim;
    int sizeDifference = nImageLargestDim - largestDimension;

    //create an image buffer to draw to
    BufferedImage imageOut = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); // 8-bit RGB
    Graphics2D g2d;
    AffineTransform tx;

    // Use a few steps if the sizes are drastically different, and only scale
    // if the desired size is smaller than the original.
    int numSteps = 0;
    if (scale < 1.0d) {
        // Make sure we have at least 1 step
        numSteps = Math.max(1, (sizeDifference / 100));
    }

    if (numSteps > 0) {
        int stepSize = sizeDifference / numSteps;
        int stepWeight = stepSize / 2;
        int heavierStepSize = stepSize + stepWeight;
        int lighterStepSize = stepSize - stepWeight;
        int currentStepSize, centerStep;
        double scaledW = imageIn.getWidth(null);
        double scaledH = imageIn.getHeight(null);

        if ((numSteps % 2) == 1) //if there's an odd number of steps
            centerStep = (int) Math.ceil((double) numSteps / 2d); //find the center step
        else
            centerStep = -1; //set it to -1 so it's ignored later

        Integer intermediateSize;
        Integer previousIntermediateSize = nImageLargestDim;

        for (Integer i = 0; i < numSteps; i++) {
            if (i + 1 != centerStep) {
                //if this isn't the center step

                if (i == numSteps - 1) {
                    //if this is the last step
                    //fix the stepsize to account for decimal place errors previously
                    currentStepSize = previousIntermediateSize - largestDimension;
                } else {
                    if (numSteps - i > numSteps / 2) //if we're in the first half of the reductions
                        currentStepSize = heavierStepSize;
                    else
                        currentStepSize = lighterStepSize;
                }
            } else {
                //center step, use natural step size
                currentStepSize = stepSize;
            }

            intermediateSize = previousIntermediateSize - currentStepSize;
            scale = intermediateSize / (double) previousIntermediateSize;
            scaledW = Math.max((int) (scaledW * scale), 1);
            scaledH = Math.max((int) (scaledH * scale), 1);

            log.info("step " + i + ": scaling to " + scaledW + " x " + scaledH);
            imageOut = new BufferedImage((int) scaledW, (int) scaledH, BufferedImage.TYPE_INT_RGB); // 8 bit RGB
            g2d = imageOut.createGraphics();
            g2d.setBackground(Color.WHITE);
            g2d.clearRect(0, 0, imageOut.getWidth(), imageOut.getHeight());
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            tx = new AffineTransform();
            tx.scale(scale, scale);
            g2d.drawImage(imageIn, tx, null);
            g2d.dispose();
            imageIn = new ImageIcon(imageOut).getImage();
            previousIntermediateSize = intermediateSize;
        }
    } else {
        // This enforces a rule that we always have an 8-bit image with white background for the thumbnail.  Plus, for large
        // images, this makes subsequent downscaling really fast because we are working on a large 8-bit image
        // instead of a large 12 or 24 bit image, so the downstream effect is very noticable.
        imageOut = new BufferedImage(imageIn.getWidth(null), imageIn.getHeight(null),
                BufferedImage.TYPE_INT_RGB);
        g2d = imageOut.createGraphics();
        g2d.setBackground(Color.WHITE);
        g2d.clearRect(0, 0, imageOut.getWidth(), imageOut.getHeight());
        tx = new AffineTransform();
        tx.setToIdentity(); //use identity matrix so image is copied exactly
        g2d.drawImage(imageIn, tx, null);
        g2d.dispose();
    }
    //saveImageAsJPEG(imageOut, fileOut);
    ImageIO.write(imageOut, "jpg", fileOut);
    return imageOut;
}

From source file:Thumbnail.java

/**
* Reads an image in a file and creates a thumbnail in another file.
* largestDimension is the largest dimension of the thumbnail, the other dimension is scaled accordingly.
* Utilises weighted stepping method to gradually reduce the image size for better results,
* i.e. larger steps to start with then smaller steps to finish with.
* Note: always writes a JPEG because GIF is protected or something - so always make your outFilename end in 'jpg'.
* PNG's with transparency are given white backgrounds
*//*  ww  w .  j  a va2  s  .c  o  m*/
public String createThumbnail(String inFilename, String outFilename, int largestDimension) {
    try {
        double scale;
        int sizeDifference, originalImageLargestDim;
        if (!inFilename.endsWith(".jpg") && !inFilename.endsWith(".jpeg") && !inFilename.endsWith(".gif")
                && !inFilename.endsWith(".png")) {
            return "Error: Unsupported image type, please only either JPG, GIF or PNG";
        } else {
            Image inImage = Toolkit.getDefaultToolkit().getImage(inFilename);
            if (inImage.getWidth(null) == -1 || inImage.getHeight(null) == -1) {
                return "Error loading file: \"" + inFilename + "\"";
            } else {
                //find biggest dimension       
                if (inImage.getWidth(null) > inImage.getHeight(null)) {
                    scale = (double) largestDimension / (double) inImage.getWidth(null);
                    sizeDifference = inImage.getWidth(null) - largestDimension;
                    originalImageLargestDim = inImage.getWidth(null);
                } else {
                    scale = (double) largestDimension / (double) inImage.getHeight(null);
                    sizeDifference = inImage.getHeight(null) - largestDimension;
                    originalImageLargestDim = inImage.getHeight(null);
                }
                //create an image buffer to draw to
                BufferedImage outImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); //arbitrary init so code compiles
                Graphics2D g2d;
                AffineTransform tx;
                if (scale < 1.0d) //only scale if desired size is smaller than original
                {
                    int numSteps = sizeDifference / 100;
                    int stepSize = sizeDifference / numSteps;
                    int stepWeight = stepSize / 2;
                    int heavierStepSize = stepSize + stepWeight;
                    int lighterStepSize = stepSize - stepWeight;
                    int currentStepSize, centerStep;
                    double scaledW = inImage.getWidth(null);
                    double scaledH = inImage.getHeight(null);
                    if (numSteps % 2 == 1) //if there's an odd number of steps
                        centerStep = (int) Math.ceil((double) numSteps / 2d); //find the center step
                    else
                        centerStep = -1; //set it to -1 so it's ignored later
                    Integer intermediateSize = originalImageLargestDim,
                            previousIntermediateSize = originalImageLargestDim;
                    Integer calculatedDim;
                    for (Integer i = 0; i < numSteps; i++) {
                        if (i + 1 != centerStep) //if this isn't the center step
                        {
                            if (i == numSteps - 1) //if this is the last step
                            {
                                //fix the stepsize to account for decimal place errors previously
                                currentStepSize = previousIntermediateSize - largestDimension;
                            } else {
                                if (numSteps - i > numSteps / 2) //if we're in the first half of the reductions
                                    currentStepSize = heavierStepSize;
                                else
                                    currentStepSize = lighterStepSize;
                            }
                        } else //center step, use natural step size
                        {
                            currentStepSize = stepSize;
                        }
                        intermediateSize = previousIntermediateSize - currentStepSize;
                        scale = (double) intermediateSize / (double) previousIntermediateSize;
                        scaledW = (int) scaledW * scale;
                        scaledH = (int) scaledH * scale;
                        outImage = new BufferedImage((int) scaledW, (int) scaledH, BufferedImage.TYPE_INT_RGB);
                        g2d = outImage.createGraphics();
                        g2d.setBackground(Color.WHITE);
                        g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight());
                        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                        tx = new AffineTransform();
                        tx.scale(scale, scale);
                        g2d.drawImage(inImage, tx, null);
                        g2d.dispose();
                        inImage = new ImageIcon(outImage).getImage();
                        previousIntermediateSize = intermediateSize;
                    }
                } else {
                    //just copy the original
                    outImage = new BufferedImage(inImage.getWidth(null), inImage.getHeight(null),
                            BufferedImage.TYPE_INT_RGB);
                    g2d = outImage.createGraphics();
                    g2d.setBackground(Color.WHITE);
                    g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight());
                    tx = new AffineTransform();
                    tx.setToIdentity(); //use identity matrix so image is copied exactly
                    g2d.drawImage(inImage, tx, null);
                    g2d.dispose();
                }
                //JPEG-encode the image and write to file.
                OutputStream os = new FileOutputStream(outFilename);
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
                encoder.encode(outImage);
                os.close();
            }
        }
    } catch (Exception ex) {
        String errorMsg = "";
        errorMsg += "<br>Exception: " + ex.toString();
        errorMsg += "<br>Cause = " + ex.getCause();
        errorMsg += "<br>Stack Trace = ";
        StackTraceElement stackTrace[] = ex.getStackTrace();
        for (int traceLine = 0; traceLine < stackTrace.length; traceLine++) {
            errorMsg += "<br>" + stackTrace[traceLine];
        }
        return errorMsg;
    }
    return ""; //success
}