Example usage for java.awt.geom AffineTransform getScaleInstance

List of usage examples for java.awt.geom AffineTransform getScaleInstance

Introduction

In this page you can find the example usage for java.awt.geom AffineTransform getScaleInstance.

Prototype

public static AffineTransform getScaleInstance(double sx, double sy) 

Source Link

Document

Returns a transform representing a scaling transformation.

Usage

From source file:org.niord.core.repo.ThumbnailService.java

/**
 * Creates a thumbnail for the image file using plain old java
 * @param file the image file//ww  w  .ja va  2 s .  c o  m
 * @param thumbFile the resulting thumbnail file
 * @param size the size of the thumbnail
 */
private void createThumbnailUsingJava(Path file, Path thumbFile, IconSize size) throws IOException {

    try {
        BufferedImage image = ImageIO.read(file.toFile());

        int w = image.getWidth();
        int h = image.getHeight();

        // Never scale up
        if (w <= size.getSize() && h <= size.getSize()) {
            FileUtils.copyFile(file.toFile(), thumbFile.toFile());

        } else {
            // Compute the scale factor
            double dx = (double) size.getSize() / (double) w;
            double dy = (double) size.getSize() / (double) h;
            double d = Math.min(dx, dy);

            // Create the thumbnail
            BufferedImage thumbImage = new BufferedImage((int) Math.round(w * d), (int) Math.round(h * d),
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = thumbImage.createGraphics();
            AffineTransform at = AffineTransform.getScaleInstance(d, d);
            g2d.drawRenderedImage(image, at);
            g2d.dispose();

            // Save the thumbnail
            ImageIO.write(thumbImage, FilenameUtils.getExtension(thumbFile.getFileName().toString()),
                    thumbFile.toFile());

            // Releas resources
            image.flush();
            thumbImage.flush();
        }

    } catch (Exception e) {
        log.error("Error creating thumbnail for image " + file, e);
        throw new IOException(e);
    }
}

From source file:org.opencms.pdftools.CmsPdfThumbnailGenerator.java

/**
 * Generates the image data for a thumbnail from a PDF.<p>
 *
 * The given width and height determine the box in which the thumbnail should fit.
 * The resulting image will always have these dimensions, even if the aspect ratio of the actual PDF
 * page is different from the ratio of the given width and height. In this case, the size of the rendered
 * page will be reduced, and the rest of the image will be filled with blank space.<p>
 *
 * If one of width or height is negative, then that dimension is chosen so the resulting aspect ratio is the
 * aspect ratio of the PDF page./*from w  ww .  ja  va  2 s . com*/
 *
 * @param pdfInputStream the input stream for reading the PDF data
 * @param boxWidth the width of the box in which the thumbnail should fit
 * @param boxHeight the height of the box in which the thumbnail should fit
 * @param imageFormat the image format (png, jpg, gif)
 * @param pageIndex the index of the page for which to render the thumbnail (starting at 0)
 *
 * @return the image data for the thumbnail, in the given image format
 * @throws Exception if something goes wrong
 */
public byte[] generateThumbnail(InputStream pdfInputStream, int boxWidth, int boxHeight, String imageFormat,
        int pageIndex) throws Exception {

    org.jpedal.io.ObjectStore.temp_dir = CmsFileUtil.normalizePath(OpenCms.getSystemInfo().getWebInfRfsPath()
            + CmsPdfThumbnailCache.PDF_CACHE_FOLDER + File.separatorChar);
    PdfDecoder decoder = new PdfDecoder(true);

    try {
        decoder.openPdfFileFromInputStream(pdfInputStream, false);
        int numPages = decoder.getPageCount();
        if (pageIndex >= numPages) {
            pageIndex = numPages - 1;
        } else if (pageIndex < 0) {
            pageIndex = 0;
        }

        // width/height are in points (1/72 of an inch)
        PdfPageData pageData = decoder.getPdfPageData();
        double aspectRatio = (pageData.getCropBoxWidth(1 + pageIndex) * 1.0)
                / pageData.getCropBoxHeight(1 + pageIndex);
        int rotation = pageData.getRotation(1 + pageIndex);
        if ((rotation == 90) || (rotation == 270)) {
            // landscape
            aspectRatio = 1 / aspectRatio;
        }

        if ((boxWidth < 0) && (boxHeight < 0)) {
            throw new IllegalArgumentException("At least one of width / height must be positive!");
        } else if ((boxWidth < 0) && (boxHeight > 0)) {
            boxWidth = (int) Math.round(aspectRatio * boxHeight);
        } else if ((boxWidth > 0) && (boxHeight < 0)) {
            boxHeight = (int) Math.round(boxWidth / aspectRatio);
        }

        // calculateDimensions only takes integers, but only their ratio matters, we multiply the box width with a big number
        int fakePixelWidth = (int) (FAKE_PIXEL_MULTIPLIER * aspectRatio);
        int fakePixelHeight = (FAKE_PIXEL_MULTIPLIER);
        int[] unpaddedThumbnailDimensions = CmsImageScaler.calculateDimension(fakePixelWidth, fakePixelHeight,
                boxWidth, boxHeight);
        decoder.decodePage(1 + pageIndex);
        BufferedImage pageImage = decoder.getPageAsImage(1 + pageIndex);
        BufferedImage paddedImage = new BufferedImage(boxWidth, boxHeight, BufferedImage.TYPE_3BYTE_BGR);

        Graphics2D g = paddedImage.createGraphics();
        int uw = unpaddedThumbnailDimensions[0];
        int uh = unpaddedThumbnailDimensions[1];

        // Scale to fit in  the box
        AffineTransformOp op = new AffineTransformOp(AffineTransform
                .getScaleInstance((uw * 1.0) / pageImage.getWidth(), (uh * 1.0) / pageImage.getHeight()),
                AffineTransformOp.TYPE_BILINEAR);

        g.setColor(Color.WHITE);
        // Fill box image with white, then draw the image data for the PDF in the middle
        g.fillRect(0, 0, paddedImage.getWidth(), paddedImage.getHeight());
        //g.drawImage(pageImage, (boxWidth - pageImage.getWidth()) / 2, (boxHeight - pageImage.getHeight()) / 2, null);
        g.drawImage(pageImage, op, (boxWidth - uw) / 2, (boxHeight - uh) / 2);
        BufferedImage pageThumbnail = paddedImage;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIOUtil.writeImage(pageThumbnail, imageFormat, out);
        byte[] imageData = out.toByteArray();
        return imageData;
    } finally {
        if (decoder.isOpen()) {
            decoder.closePdfFile();
        }
        pdfInputStream.close();

    }
}

From source file:org.openstreetmap.gui.jmapviewer.Tile.java

/**
 * Tries to get tiles of a lower or higher zoom level (one or two level
 * difference) from cache and use it as a placeholder until the tile has
 * been loaded.//from  w  w w. ja v  a 2  s . c  o m
 */
public void loadPlaceholderFromCache(TileCache cache) {
    BufferedImage tmpImage = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = (Graphics2D) tmpImage.getGraphics();
    // g.drawImage(image, 0, 0, null);
    for (int zoomDiff = 1; zoomDiff < 5; zoomDiff++) {
        // first we check if there are already the 2^x tiles
        // of a higher detail level
        int zoom_high = zoom + zoomDiff;
        if (zoomDiff < 3 && zoom_high <= JMapViewer.MAX_ZOOM) {
            int factor = 1 << zoomDiff;
            int xtile_high = xtile << zoomDiff;
            int ytile_high = ytile << zoomDiff;
            double scale = 1.0 / factor;
            g.setTransform(AffineTransform.getScaleInstance(scale, scale));
            int paintedTileCount = 0;
            for (int x = 0; x < factor; x++) {
                for (int y = 0; y < factor; y++) {
                    Tile tile = cache.getTile(source, xtile_high + x, ytile_high + y, zoom_high);
                    if (tile != null && tile.isLoaded()) {
                        paintedTileCount++;
                        tile.paint(g, x * SIZE, y * SIZE);
                    }
                }
            }
            if (paintedTileCount == factor * factor) {
                image = tmpImage;
                return;
            }
        }

        int zoom_low = zoom - zoomDiff;
        if (zoom_low >= JMapViewer.MIN_ZOOM) {
            int xtile_low = xtile >> zoomDiff;
            int ytile_low = ytile >> zoomDiff;
            int factor = (1 << zoomDiff);
            double scale = factor;
            AffineTransform at = new AffineTransform();
            int translate_x = (xtile % factor) * SIZE;
            int translate_y = (ytile % factor) * SIZE;
            at.setTransform(scale, 0, 0, scale, -translate_x, -translate_y);
            g.setTransform(at);
            Tile tile = cache.getTile(source, xtile_low, ytile_low, zoom_low);
            if (tile != null && tile.isLoaded()) {
                tile.paint(g, 0, 0);
                image = tmpImage;
                return;
            }
        }
    }
}

From source file:org.openstreetmap.josm.gui.layer.geoimage.ThumbsLoader.java

private BufferedImage loadThumb(ImageEntry entry) {
    final String cacheIdent = entry.getFile().toString() + ':' + maxSize;

    if (!cacheOff && cache != null) {
        try {/*  w  w  w  . ja  va  2 s.  com*/
            BufferedImageCacheEntry cacheEntry = cache.get(cacheIdent);
            if (cacheEntry != null && cacheEntry.getImage() != null) {
                Logging.debug(" from cache");
                return cacheEntry.getImage();
            }
        } catch (IOException e) {
            Logging.warn(e);
        }
    }

    Image img = Toolkit.getDefaultToolkit().createImage(entry.getFile().getPath());
    tracker.addImage(img, 0);
    try {
        tracker.waitForID(0);
    } catch (InterruptedException e) {
        Logging.error(" InterruptedException while loading thumb");
        Thread.currentThread().interrupt();
        return null;
    }
    if (tracker.isErrorID(1) || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) {
        Logging.error(" Invalid image");
        return null;
    }

    final int w = img.getWidth(null);
    final int h = img.getHeight(null);
    final int hh, ww;
    final Integer exifOrientation = entry.getExifOrientation();
    if (exifOrientation != null && ExifReader.orientationSwitchesDimensions(exifOrientation)) {
        ww = h;
        hh = w;
    } else {
        ww = w;
        hh = h;
    }

    Rectangle targetSize = ImageDisplay.calculateDrawImageRectangle(new Rectangle(0, 0, ww, hh),
            new Rectangle(0, 0, maxSize, maxSize));
    BufferedImage scaledBI = new BufferedImage(targetSize.width, targetSize.height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = scaledBI.createGraphics();

    final AffineTransform scale = AffineTransform.getScaleInstance((double) targetSize.width / ww,
            (double) targetSize.height / hh);
    if (exifOrientation != null) {
        final AffineTransform restoreOrientation = ExifReader.getRestoreOrientationTransform(exifOrientation, w,
                h);
        scale.concatenate(restoreOrientation);
    }

    while (!g.drawImage(img, scale, null)) {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            Logging.warn("InterruptedException while drawing thumb");
            Thread.currentThread().interrupt();
        }
    }
    g.dispose();
    tracker.removeImage(img);

    if (scaledBI.getWidth() <= 0 || scaledBI.getHeight() <= 0) {
        Logging.error(" Invalid image");
        return null;
    }

    if (!cacheOff && cache != null) {
        try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
            ImageIO.write(scaledBI, "png", output);
            cache.put(cacheIdent, new BufferedImageCacheEntry(output.toByteArray()));
        } catch (IOException e) {
            Logging.warn("Failed to save geoimage thumb to cache");
            Logging.warn(e);
        }
    }

    return scaledBI;
}

From source file:org.pentaho.reporting.engine.classic.core.function.PaintDynamicComponentFunction.java

/**
 * Creates the component.//w  w w  .ja  v a 2 s  .com
 *
 * @return the created image or null, if no image could be created.
 */
private Image createComponentImage() {
    final Object o = getDataRow().get(getField());
    if ((o instanceof Component) == false) {
        return null;
    }

    final float scale = getScale() * getDeviceScale();

    final ComponentDrawable drawable = new ComponentDrawable();
    drawable.setComponent((Component) o);
    drawable.setAllowOwnPeer(true);
    drawable.setPaintSynchronized(true);
    final Dimension dim = drawable.getSize();

    final int width = Math.max(1, (int) (scale * dim.width));
    final int height = Math.max(1, (int) (scale * dim.height));

    final BufferedImage bi = ImageUtils.createTransparentImage(width, height);
    final Graphics2D graph = bi.createGraphics();
    graph.setBackground(new Color(0, 0, 0, 0));
    graph.setTransform(AffineTransform.getScaleInstance(scale, scale));
    drawable.draw(graph, new Rectangle2D.Float(0, 0, dim.width, dim.height));
    graph.dispose();

    return bi;
}

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

/**
 * @param content//ww  w.ja  v  a  2  s.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.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfGraphics2D.java

@Override
public void drawString(final String s, final float x, float y) {
    if (s.length() == 0) {
        return;/* w  w w.  j  a  v  a 2s .  com*/
    }
    setFillPaint();
    setStrokePaint();

    final AffineTransform at = getTransform();
    final AffineTransform at2 = getTransform();
    at2.translate(x, y);
    at2.concatenate(font.getTransform());
    setTransform(at2);
    final AffineTransform inverse = this.normalizeMatrix();
    final AffineTransform flipper = FLIP_TRANSFORM;
    inverse.concatenate(flipper);
    final double[] mx = new double[6];
    inverse.getMatrix(mx);
    cb.beginText();

    final float fontSize = font.getSize2D();
    if (lastBaseFont == null) {
        final String fontName = font.getName();
        final boolean bold = font.isBold();
        final boolean italic = font.isItalic();

        final BaseFontFontMetrics fontMetrics = metaData.getBaseFontFontMetrics(fontName, fontSize, bold,
                italic, null, metaData.isFeatureSupported(OutputProcessorFeature.EMBED_ALL_FONTS), false);
        final FontNativeContext nativeContext = fontMetrics.getNativeContext();
        lastBaseFont = fontMetrics.getBaseFont();

        cb.setFontAndSize(lastBaseFont, fontSize);
        if (fontMetrics.isTrueTypeFont() && bold && nativeContext.isNativeBold() == false) {
            final float strokeWidth = font.getSize2D() / 30.0f; // right from iText ...
            if (strokeWidth == 1) {
                cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
            } else {
                cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
                cb.setLineWidth(strokeWidth);
            }
        } else {
            cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
        }
    } else {
        cb.setFontAndSize(lastBaseFont, fontSize);
    }

    cb.setTextMatrix((float) mx[0], (float) mx[1], (float) mx[2], (float) mx[3], (float) mx[4], (float) mx[5]);
    double width = 0;
    if (fontSize > 0) {
        final float scale = 1000 / fontSize;
        final Font font = this.font.deriveFont(AffineTransform.getScaleInstance(scale, scale));
        final Rectangle2D stringBounds = font.getStringBounds(s, getFontRenderContext());
        width = stringBounds.getWidth() / scale;
    }
    if (s.length() > 1) {
        final float adv = ((float) width - lastBaseFont.getWidthPoint(s, fontSize)) / (s.length() - 1);
        cb.setCharacterSpacing(adv);
    }
    cb.showText(s);
    if (s.length() > 1) {
        cb.setCharacterSpacing(0);
    }
    cb.endText();
    setTransform(at);
    if (underline) {
        // These two are supposed to be taken from the .AFM file
        // int UnderlinePosition = -100;
        final int UnderlineThickness = 50;
        //
        final double d = PdfGraphics2D.asPoints(UnderlineThickness, (int) fontSize);
        setStroke(new BasicStroke((float) d));
        y = (float) ((y) + PdfGraphics2D.asPoints((UnderlineThickness), (int) fontSize));
        final Line2D line = new Line2D.Double(x, y, (width + x), y);
        draw(line);
    }
}

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

protected boolean drawImage(final RenderableReplacedContentBox content, final Image image,
        final com.lowagie.text.Image itextImage) {
    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) {
        PdfLogicalPageDrawable.logger.debug("Error: Image area is empty: " + content);
        return false;
    }//from   w w  w .java  2s  .c om

    final 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 = getMetaData()
                .getNumericFeatureValue(OutputProcessorFeature.DEVICE_RESOLUTION);
        if (getMetaData().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);
        scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
    }

    final PdfGraphics2D pdfGraphics2D = (PdfGraphics2D) g2;
    pdfGraphics2D.drawPdfImage(itextImage, image, scaleTransform, null);
    g2.dispose();
    return true;
}

From source file:org.risk.model.MapVisualization.java

/**
 * This method is used to map the Capital and Continent to the the State
 * //from   w  w w .  j  ava  2  s .  com
 * @param state      is the arraylist of state objects
 */
private void mapCapitalAndContinentToState() {

    Transformer<Integer, Shape> vertexSize = new Transformer<Integer, Shape>() {
        public Shape transform(Integer i) {
            switch (states.get(i - 1).getContinentID()) {
            case Constants.CONTINENT1ID:
                if (states.get(i - 1).getIsCapital()) {
                    return AffineTransform.getScaleInstance(1.5, 1.5)
                            .createTransformedShape(Constants.CONTINENT1SHAPE);
                } else {
                    return Constants.CONTINENT1SHAPE;
                }
            case Constants.CONTINENT2ID:
                if (states.get(i - 1).getIsCapital()) {
                    return AffineTransform.getScaleInstance(1.5, 1.5)
                            .createTransformedShape(Constants.CONTINENT2SHAPE);
                } else {
                    return Constants.CONTINENT2SHAPE;
                }
            case Constants.CONTINENT3ID:
                if (states.get(i - 1).getIsCapital()) {
                    return AffineTransform.getScaleInstance(1.5, 1.5)
                            .createTransformedShape(Constants.CONTINENT3SHAPE);
                } else {
                    return Constants.CONTINENT3SHAPE;
                }
            case Constants.CONTINENT4ID:
                if (states.get(i - 1).getIsCapital()) {
                    return AffineTransform.getScaleInstance(1.5, 1.5)
                            .createTransformedShape(Constants.CONTINENT4SHAPE);
                } else {
                    return Constants.CONTINENT4SHAPE;
                }
            case Constants.CONTINENT5ID:
                if (states.get(i - 1).getIsCapital()) {
                    return AffineTransform.getScaleInstance(1.5, 1.5)
                            .createTransformedShape(Constants.CONTINENT5SHAPE);
                } else {
                    return Constants.CONTINENT5SHAPE;
                }
            case Constants.CONTINENT6ID:
                if (states.get(i - 1).getIsCapital()) {
                    return AffineTransform.getScaleInstance(1.5, 1.5)
                            .createTransformedShape(Constants.CONTINENT6SHAPE);
                } else {
                    return Constants.CONTINENT6SHAPE;
                }
            case Constants.CONTINENT7ID:
                if (states.get(i - 1).getIsCapital()) {
                    return AffineTransform.getScaleInstance(1.5, 1.5)
                            .createTransformedShape(Constants.CONTINENT7SHAPE);
                } else {
                    return Constants.CONTINENT7SHAPE;
                }
            default:
                return Constants.CONTINENT1SHAPE;
            }
        }

    };
    vv.getRenderContext().setVertexShapeTransformer(vertexSize);
}

From source file:org.sbs.util.ImageCompress.java

/**
 * ?// www . ja  v a  2 s .  co m
 * 
 * @param source
 * @param targetW
 * @param targetH
 * @return
 */
public BufferedImage resize(BufferedImage source, int targetW, int targetH) {
    // targetWtargetH
    int desH = 0;
    int type = source.getType();
    BufferedImage target = null;
    double sx = (double) targetW / source.getWidth();
    double sy = sx;
    desH = (int) (sx * source.getHeight());
    if (desH < targetH) {
        desH = targetH;
        sy = (double) 61 / source.getHeight();
    }
    if (type == BufferedImage.TYPE_CUSTOM) { // handmade
        ColorModel cm = source.getColorModel();
        WritableRaster raster = cm.createCompatibleWritableRaster(targetW, desH);
        boolean alphaPremultiplied = cm.isAlphaPremultiplied();
        target = new BufferedImage(cm, raster, alphaPremultiplied, null);
    } else
        target = new BufferedImage(targetW, desH, type);
    Graphics2D g = target.createGraphics();
    // smoother than exlax:
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
    g.dispose();
    return target;
}