Example usage for java.awt Graphics2D drawRenderedImage

List of usage examples for java.awt Graphics2D drawRenderedImage

Introduction

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

Prototype

public abstract void drawRenderedImage(RenderedImage img, AffineTransform xform);

Source Link

Document

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

Usage

From source file:org.geowebcache.service.wms.WMSTileFuser.java

protected void scaleRaster() {
    if (canvasSize[0] != reqWidth || canvasSize[1] != reqHeight) {
        BufferedImage preTransform = canvas;

        canvas = new BufferedImage(reqWidth, reqHeight, preTransform.getType());

        Graphics2D gfx = canvas.createGraphics();

        AffineTransform affineTrans = AffineTransform.getScaleInstance(
                ((double) reqWidth) / preTransform.getWidth(), ((double) reqHeight) / preTransform.getHeight());

        log.debug("AffineTransform: " + (((double) reqWidth) / preTransform.getWidth()) + ","
                + +(((double) reqHeight) / preTransform.getHeight()));
        // Hints settings
        RenderingHints hintsTemp = HintsLevel.DEFAULT.getRenderingHints();

        if (hints != null) {
            hintsTemp = hints;//from   w  w w.ja  va2 s .  c  om
        }
        gfx.addRenderingHints(hintsTemp);
        gfx.drawRenderedImage(preTransform, affineTrans);
        gfx.dispose();
    }
}

From source file:skoa.helpers.Graficos.java

private BufferedImage convertirTipo(BufferedImage i1, int tipo) {
    BufferedImage res = new BufferedImage(i1.getWidth(), i1.getHeight(), tipo);
    Graphics2D g = res.createGraphics();
    g.drawRenderedImage(i1, null);
    g.dispose();//from w  ww. j  av a  2  s.  c om
    return res;
}

From source file:nl.ctmm.trait.proteomics.qcviewer.utils.Utilities.java

/**
 * Scale the supplied image to the specified width and height. The scale type is either {@link Utilities#SCALE_FIT}
 * to make the scaled image fit within the width by height rectangle or {@link Utilities#SCALE_FILL} to make the
 * scaled image fill the entire rectangle (and possibly go outside it in one dimension).
 *
 * @param image     the image to be scaled.
 * @param scaleType {@link Utilities#SCALE_FIT} or {@link Utilities#SCALE_FILL}.
 * @param width     the preferred width.
 * @param height    the preferred height.
 * @return the scaled image.//from   w w w  .ja  va  2  s  .  co m
 */
public static BufferedImage scaleImage(final BufferedImage image, final int scaleType, final int width,
        final int height) {
    logger.fine("scaleImage: width: " + width + " height: " + height);

    /* TODO: can we do the scaling once and save the images of the right size? [Freek]
     * This is a good idea. [Pravin]  
     * 
     * TODO: are there classes in the standard Java libraries or third party libraries that do this scaling? [Freek]
     * return image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
     * This article describes use of Greaphics2D.drawImage() [Pravin]
     * http://www.mkyong.com/java/how-to-resize-an-image-in-java/
     * imgscalr is Java image scaling library available under Apache 2 License. 
     * http://www.thebuzzmedia.com/software/imgscalr-java-image-scaling-library/
     */
    final BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    final Graphics2D graphics2D = scaledImage.createGraphics();
    graphics2D.setColor(Color.white);
    graphics2D.fillRect(0, 0, width, height);
    final double imageWidth = image.getWidth();
    final double imageHeight = image.getHeight();
    final double xScale = width / imageWidth;
    final double yScale = height / imageHeight;
    double scale = 1.0;
    switch (scaleType) {
    case SCALE_FIT:
        scale = Math.min(xScale, yScale);
        break;
    case SCALE_FILL:
        scale = Math.max(xScale, yScale);
        break;
    default:
        logger.warning(String.format("Unexpected scale type: %d.", scaleType));
        break;
    }
    final double x = (width - imageWidth * scale) / 2;
    final double y = (height - imageHeight * scale) / 2;
    final AffineTransform affineTransform = AffineTransform.getTranslateInstance(x, y);
    affineTransform.scale(scale, scale);
    graphics2D.drawRenderedImage(image, affineTransform);
    graphics2D.dispose();
    return scaledImage;
}

From source file:opennlp.tools.similarity.apps.utils.Utils.java

public static boolean createResizedCopy(String originalImage, String newImage, int scaledWidth,
        int scaledHeight) {
    boolean retVal = true;
    try {/*from ww  w  .j  a va 2  s  .  c  om*/
        File o = new File(originalImage);
        BufferedImage bsrc = ImageIO.read(o);
        BufferedImage bdest = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);

        Graphics2D g = bdest.createGraphics();
        AffineTransform at = AffineTransform.getScaleInstance((double) scaledWidth / bsrc.getWidth(),
                (double) scaledHeight / bsrc.getHeight());
        g.drawRenderedImage(bsrc, at);
        ImageIO.write(bdest, "jpeg", new File(newImage));

    } catch (Exception e) {
        retVal = false;
        LOG.severe("Failed creating thumbnail for image: " + originalImage + e);
    }

    return retVal;
}

From source file:org.apache.fop.render.pcl.PCLGenerator.java

private RenderedImage getMask(RenderedImage img, Dimension targetDim) {
    ColorModel cm = img.getColorModel();
    if (cm.hasAlpha()) {
        BufferedImage alpha = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        Raster raster = img.getData();
        GraphicsUtil.copyBand(raster, cm.getNumColorComponents(), alpha.getRaster(), 0);

        BufferedImageOp op1 = new LookupOp(new ByteLookupTable(0, THRESHOLD_TABLE), null);
        BufferedImage alphat = op1.filter(alpha, null);

        BufferedImage mask;//  w w w .jav a  2 s  .  c  o  m
        if (true) {
            mask = new BufferedImage(targetDim.width, targetDim.height, BufferedImage.TYPE_BYTE_BINARY);
        } else {
            byte[] arr = { (byte) 0, (byte) 0xff };
            ColorModel colorModel = new IndexColorModel(1, 2, arr, arr, arr);
            WritableRaster wraster = Raster.createPackedRaster(DataBuffer.TYPE_BYTE, targetDim.width,
                    targetDim.height, 1, 1, null);
            mask = new BufferedImage(colorModel, wraster, false, null);
        }

        Graphics2D g2d = mask.createGraphics();
        try {
            AffineTransform at = new AffineTransform();
            double sx = targetDim.getWidth() / img.getWidth();
            double sy = targetDim.getHeight() / img.getHeight();
            at.scale(sx, sy);
            g2d.drawRenderedImage(alphat, at);
        } finally {
            g2d.dispose();
        }
        /*
        try {
        BatchDiffer.saveAsPNG(alpha, new java.io.File("D:/out-alpha.png"));
        BatchDiffer.saveAsPNG(mask, new java.io.File("D:/out-mask.png"));
        } catch (IOException e) {
        e.printStackTrace();
        }*/
        return mask;
    } else {
        return null;
    }
}

From source file:org.esa.nest.dat.layers.maptools.components.CompassComponent.java

public void render(final Graphics2D graphics, final ScreenPixelConverter screenPixel) {
    if (Double.isNaN(angle))
        return;//from   www  .ja v  a2  s.co m

    final AffineTransform transformSave = graphics.getTransform();
    try {
        final AffineTransform transform = screenPixel.getImageTransform(transformSave);

        final double scale = (marginPct * 2 * rasterWidth) / (double) image.getWidth();
        transform.translate(point1.x, point1.y);
        transform.scale(scale, scale);
        transform.rotate(angle);

        graphics.drawRenderedImage(image, transform);
    } finally {
        graphics.setTransform(transformSave);
    }
}

From source file:org.h819.commons.file.MyPDFUtilss.java

/**
 *  pdf ? pdf/* w  w w  .  j a  v  a2  s  .c  o m*/
 *
 * @param srcPdf      the original PDF
 * @param destPdf     the resulting PDF
 * @param imageFactor The multiplication factor for the image (?  imageFacto =0.5f)
 * @throws IOException
 * @throws DocumentException
 */
public static void compressPdf(File srcPdf, File destPdf, float imageFactor)
        throws IOException, DocumentException {

    PdfReader reader = new PdfReader(srcPdf.getAbsolutePath());
    int n = reader.getXrefSize();
    PdfObject object;
    PRStream stream;
    // Look for image and manipulate image stream
    for (int i = 0; i < n; i++) {
        object = reader.getPdfObject(i);
        if (object == null || !object.isStream())
            continue;
        stream = (PRStream) object;
        if (!PdfName.IMAGE.equals(stream.getAsName(PdfName.SUBTYPE)))
            continue;
        if (!PdfName.DCTDECODE.equals(stream.getAsName(PdfName.FILTER)))
            continue;
        PdfImageObject image = new PdfImageObject(stream);
        BufferedImage bi = image.getBufferedImage();
        if (bi == null)
            continue;
        int width = (int) (bi.getWidth() * imageFactor);
        int height = (int) (bi.getHeight() * imageFactor);
        if (width <= 0 || height <= 0)
            continue;
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        AffineTransform at = AffineTransform.getScaleInstance(imageFactor, imageFactor);
        Graphics2D g = img.createGraphics();
        g.drawRenderedImage(bi, at);
        ByteArrayOutputStream imgBytes = new ByteArrayOutputStream();
        ImageIO.write(img, "JPG", imgBytes);
        stream.clear();
        stream.setData(imgBytes.toByteArray(), false, PRStream.NO_COMPRESSION);
        stream.put(PdfName.TYPE, PdfName.XOBJECT);
        stream.put(PdfName.SUBTYPE, PdfName.IMAGE);
        stream.put(PdfName.FILTER, PdfName.DCTDECODE);
        stream.put(PdfName.WIDTH, new PdfNumber(width));
        stream.put(PdfName.HEIGHT, new PdfNumber(height));
        stream.put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
        stream.put(PdfName.COLORSPACE, PdfName.DEVICERGB);
    }
    reader.removeUnusedObjects();
    // Save altered PDF
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destPdf.getAbsolutePath()));
    stamper.setFullCompression();
    stamper.close();
    reader.close();
}

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/*from   w  ww  .j  av  a2s  . c  om*/
 * @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.sbs.util.ImageCompress.java

/**
 * ?//  w  ww .  j  av a 2s.  com
 * 
 * @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;
}

From source file:org.squidy.designer.util.ImageUtils.java

/**
 * @param source/*w  w w  .j  ava 2 s.com*/
 * @param width
 * @param height
 * @return
 * @throws IOException
 */
public static BufferedImage scale(BufferedImage source, int width, int height) throws IOException {

    BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = target.createGraphics();
    AffineTransform at = AffineTransform.getScaleInstance((double) width / source.getWidth(),
            (double) height / source.getHeight());
    g.drawRenderedImage(source, at);

    return target;
}