Example usage for java.awt.image AffineTransformOp TYPE_BILINEAR

List of usage examples for java.awt.image AffineTransformOp TYPE_BILINEAR

Introduction

In this page you can find the example usage for java.awt.image AffineTransformOp TYPE_BILINEAR.

Prototype

int TYPE_BILINEAR

To view the source code for java.awt.image AffineTransformOp TYPE_BILINEAR.

Click Source Link

Document

Bilinear interpolation type.

Usage

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.//  w  w w  .  jav a2 s .  c  o m
 *
 * @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:com.ttech.cordovabuild.domain.application.source.ApplicationSourceFactoryImpl.java

public static BufferedImage scaleTo(BufferedImage image, Integer height, Integer width) throws IOException {
    int imageWidth = image.getWidth();
    int imageHeight = image.getHeight();

    double scaleX = (double) (width == null ? 1 : width / imageWidth);
    double scaleY = (double) (height == null ? 1 : height / imageHeight);
    AffineTransform scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
    AffineTransformOp bilinearScaleOp = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_BILINEAR);

    return bilinearScaleOp.filter(image, new BufferedImage(width, height, image.getType()));
}

From source file:org.geolatte.maprenderer.sld.graphics.ExternalGraphicsRepository.java

private BufferedImage rotate(BufferedImage img, float rotation) {
    AffineTransform tx = new AffineTransform();
    //determine center point of image
    int sx = img.getMinX() + img.getWidth() / 2;
    int sy = img.getMinY() + img.getHeight() / 2;
    double theta = Math.toRadians(rotation);
    tx.rotate(theta, sx, sy);/*w w  w.  j  a  va 2  s  .  co  m*/
    AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
    return op.filter(img, null);
}

From source file:org.apache.cocoon.reading.ImageReader.java

protected void processStream(InputStream inputStream) throws IOException, ProcessingException {
    if (hasTransform()) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("image " + ((width == 0) ? "?" : Integer.toString(width)) + "x"
                    + ((height == 0) ? "?" : Integer.toString(height)) + " expires: " + expires);
        }/*  www  .  j  av a  2 s  .c om*/

        /*
         * NOTE (SM):
         * Due to Bug Id 4502892 (which is found in *all* JVM implementations from
         * 1.2.x and 1.3.x on all OS!), we must buffer the JPEG generation to avoid
         * that connection resetting by the peer (user pressing the stop button,
         * for example) crashes the entire JVM (yes, dude, the bug is *that* nasty
         * since it happens in JPEG routines which are native!)
         * I'm perfectly aware of the huge memory problems that this causes (almost
         * doubling memory consuption for each image and making the GC work twice
         * as hard) but it's *far* better than restarting the JVM every 2 minutes
         * (since this is the average experience for image-intensive web application
         * such as an image gallery).
         * Please, go to the <a href="http://developer.java.sun.com/developer/bugParade/bugs/4502892.html">Sun Developers Connection</a>
         * and vote this BUG as the one you would like fixed sooner rather than
         * later and all this hack will automagically go away.
         * Many deep thanks to Michael Hartle <mhartle@hartle-klug.com> for tracking
         * this down and suggesting the workaround.
         *
         * UPDATE (SM):
         * This appears to be fixed on JDK 1.4
         */

        try {
            byte content[] = readFully(inputStream);
            ImageIcon icon = new ImageIcon(content);
            BufferedImage original = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),
                    BufferedImage.TYPE_INT_RGB);
            BufferedImage currentImage = original;
            currentImage.getGraphics().drawImage(icon.getImage(), 0, 0, null);

            if (width > 0 || height > 0) {
                double ow = icon.getImage().getWidth(null);
                double oh = icon.getImage().getHeight(null);

                if (usePercent) {
                    if (width > 0) {
                        width = Math.round((int) (ow * width) / 100);
                    }
                    if (height > 0) {
                        height = Math.round((int) (oh * height) / 100);
                    }
                }

                AffineTransformOp filter = new AffineTransformOp(getTransform(ow, oh, width, height),
                        AffineTransformOp.TYPE_BILINEAR);
                WritableRaster scaledRaster = filter.createCompatibleDestRaster(currentImage.getRaster());

                filter.filter(currentImage.getRaster(), scaledRaster);

                currentImage = new BufferedImage(original.getColorModel(), scaledRaster, true, null);
            }

            if (null != grayscaleFilter) {
                grayscaleFilter.filter(currentImage, currentImage);
            }

            if (null != colorFilter) {
                colorFilter.filter(currentImage, currentImage);
            }

            // JVM Bug handling
            if (JVMBugFixed) {
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                JPEGEncodeParam p = encoder.getDefaultJPEGEncodeParam(currentImage);
                p.setQuality(this.quality[0], true);
                encoder.setJPEGEncodeParam(p);
                encoder.encode(currentImage);
            } else {
                ByteArrayOutputStream bstream = new ByteArrayOutputStream();
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bstream);
                JPEGEncodeParam p = encoder.getDefaultJPEGEncodeParam(currentImage);
                p.setQuality(this.quality[0], true);
                encoder.setJPEGEncodeParam(p);
                encoder.encode(currentImage);
                out.write(bstream.toByteArray());
            }

            out.flush();
        } catch (ImageFormatException e) {
            throw new ProcessingException(
                    "Error reading the image. " + "Note that only JPEG images are currently supported.");
        } finally {
            // Bugzilla Bug 25069, close inputStream in finally block
            // this will close inputStream even if processStream throws
            // an exception
            inputStream.close();
        }
    } else {
        // only read the resource - no modifications requested
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("passing original resource");
        }
        super.processStream(inputStream);
    }
}

From source file:org.alfresco.extension.countersign.action.executer.PDFSignatureProviderActionExecuter.java

/**
 * Scales the signature image to fit the provided signature field dimensions,
 * preserving the aspect ratio//from w  w w .ja v  a2 s  . com
 * 
 * @param signatureImage
 * @param width
 * @param height
 * @return
 */
private BufferedImage scaleSignature(BufferedImage signatureImage, int width, int height) {
    if (signatureImage.getHeight() > height) {
        BufferedImage scaled = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        AffineTransform at = new AffineTransform();
        at.scale(2.0, 2.0);
        AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
        scaled = scaleOp.filter(signatureImage, scaled);
        return scaled;
    } else {
        return signatureImage;
    }
}

From source file:com.flexive.shared.media.impl.FxMediaNativeEngine.java

/**
 * Rotate an image using the requested angle
 *
 * @param bufferedImage imeg to rotate//from   w  w  w.ja  v  a 2s. c om
 * @param angle         angle to rotate
 * @return BufferedImage containing the rotation
 */
@SuppressWarnings({ "UnusedAssignment" })
private static BufferedImage rotate(BufferedImage bufferedImage, int angle) {
    angle = angle % 360;
    if (angle == 0)
        return bufferedImage;
    if (angle < 0)
        angle += 360;
    switch (angle) {
    case 90:
        BufferedImageOp rot90 = new AffineTransformOp(AffineTransform.getRotateInstance(Math.PI / 2.0,
                bufferedImage.getHeight() / 2.0, bufferedImage.getHeight() / 2.0),
                AffineTransformOp.TYPE_BILINEAR);
        BufferedImage img90 = new BufferedImage(bufferedImage.getHeight(), bufferedImage.getWidth(),
                bufferedImage.getType());
        return rot90.filter(bufferedImage, img90);
    case 180:
        BufferedImageOp rot180 = new AffineTransformOp(AffineTransform.getRotateInstance(Math.PI,
                bufferedImage.getWidth() / 2.0, bufferedImage.getHeight() / 2.0),
                AffineTransformOp.TYPE_BILINEAR);
        BufferedImage img180 = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(),
                bufferedImage.getType());
        return rot180.filter(bufferedImage, img180);
    case 270:
        BufferedImageOp rot270 = new AffineTransformOp(AffineTransform.getRotateInstance(-Math.PI / 2.0,
                bufferedImage.getWidth() / 2.0, bufferedImage.getWidth() / 2.0),
                AffineTransformOp.TYPE_BILINEAR);
        BufferedImage img270 = new BufferedImage(bufferedImage.getHeight(), bufferedImage.getWidth(),
                bufferedImage.getType());
        return rot270.filter(bufferedImage, img270);
    default:
        //rotate using a non-standard angle (have to draw a box around the image that can fit it)
        int box = (int) Math.sqrt(bufferedImage.getHeight() * bufferedImage.getHeight()
                + bufferedImage.getWidth() * bufferedImage.getWidth());
        BufferedImage imgFree = new BufferedImage(box, box, bufferedImage.getType());
        BufferedImage imgRet = new BufferedImage(box, box, bufferedImage.getType());
        Graphics2D g = imgFree.createGraphics();
        if (bufferedImage.getTransparency() == Transparency.OPAQUE) {
            //draw a white background on opaque images since they dont support transparency
            g.setBackground(Color.WHITE);
            g.clearRect(0, 0, box, box);
            Graphics2D gr = imgRet.createGraphics();
            gr.setBackground(Color.WHITE);
            gr.clearRect(0, 0, box, box);
            gr = null;
        }
        g.drawImage(bufferedImage, box / 2 - bufferedImage.getWidth() / 2,
                box / 2 - bufferedImage.getHeight() / 2, bufferedImage.getWidth(), bufferedImage.getHeight(),
                null);
        g = null;
        AffineTransform at = new AffineTransform();
        at.rotate(angle * Math.PI / 180.0, box / 2.0, box / 2.0);
        BufferedImageOp bio;
        bio = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
        return bio.filter(imgFree, imgRet);
    }
}

From source file:org.apache.cocoon.reading.RepoImageReader.java

/**
 * @return the time the read source was last modified or 0 if it is not
 *         possible to detect//from w  w  w  .  ja va  2  s .c  o  m
 */
/*
public long getLastModified() {
if (hasRanges()) {
    // This is a byte range request so we can't use the cache, return null.
    return 0;
}
        
if (quickTest) {
    return inputSource.getLastModified();
}
        
final String systemId = (String) documents.get(request.getRequestURI());
// Note: getURI() might be null in some incomplete implementations
final String sourceURI = inputSource.getURI();
if (systemId == null || (sourceURI != null && sourceURI.equals(systemId))) {
    return inputSource.getLastModified();
}
        
documents.remove(request.getRequestURI());
return 0;
}*/

protected void processStream(InputStream inputStream) throws IOException, ProcessingException {

    if (inputStream != null) {
        if (hasTransform()) {
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("image " + ((width == 0) ? "?" : Integer.toString(width)) + "x"
                        + ((height == 0) ? "?" : Integer.toString(height)) + " expires: " + expires);
            }

            try {
                byte content[] = readFully(inputStream);
                ImageIcon icon = new ImageIcon(content);
                BufferedImage original = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),
                        BufferedImage.TYPE_INT_RGB);
                BufferedImage currentImage = original;
                currentImage.getGraphics().drawImage(icon.getImage(), 0, 0, null);

                if (width > 0 || height > 0) {
                    double ow = icon.getImage().getWidth(null);
                    double oh = icon.getImage().getHeight(null);

                    if (usePercent) {
                        if (width > 0) {
                            width = Math.round((int) (ow * width) / 100);
                        }
                        if (height > 0) {
                            height = Math.round((int) (oh * height) / 100);
                        }
                    }

                    AffineTransformOp filter = new AffineTransformOp(getTransform(ow, oh, width, height),
                            AffineTransformOp.TYPE_BILINEAR);
                    WritableRaster scaledRaster = filter.createCompatibleDestRaster(currentImage.getRaster());

                    filter.filter(currentImage.getRaster(), scaledRaster);

                    currentImage = new BufferedImage(original.getColorModel(), scaledRaster, true, null);
                }

                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                JPEGEncodeParam p = encoder.getDefaultJPEGEncodeParam(currentImage);
                p.setQuality(this.quality[0], true);
                encoder.setJPEGEncodeParam(p);
                encoder.encode(currentImage);

                out.flush();
            } catch (ImageFormatException e) {
                throw new ProcessingException(
                        "Error reading the image. " + "Note that only JPEG images are currently supported.");
            } finally {
                // Bugzilla Bug 25069, close inputStream in finally block
                // this will close inputStream even if processStream throws
                // an exception
                inputStream.close();
            }
        } else {
            try {
                InputStream is = inputStream;

                long expires = parameters.getParameterAsInteger("expires", -1);
                if (expires > 0) {
                    response.setDateHeader("Expires", System.currentTimeMillis() + expires);
                }
                response.setHeader("Accept-Ranges", "bytes");

                byte[] buffer = new byte[8192];
                int length;
                while ((length = is.read(buffer)) > -1) {
                    out.write(buffer, 0, length);
                }
                is.close();
                out.flush();
            } catch (RuntimeException e) {
                throw e;
            } finally {
                // Bugzilla Bug 25069, close inputStream in finally block
                // this will close inputStream even if processStream throws
                // an exception
                inputStream.close();
            }

        }
    } else {
        throw new IOException("Deals: Problem, resource not found or Repository not working correctly");
    }

}

From source file:org.apache.batchee.tools.maven.doc.DiagramGenerator.java

private void saveView(final Dimension currentSize, final Dimension desiredSize, final String name,
        final VisualizationViewer<Node, Edge> viewer) {
    BufferedImage bi = new BufferedImage(currentSize.width, currentSize.height, BufferedImage.TYPE_INT_ARGB);

    final Graphics2D g = bi.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

    final boolean db = viewer.isDoubleBuffered();
    viewer.setDoubleBuffered(false);//  www  .  j a v  a  2  s.  c o  m
    viewer.paint(g);
    viewer.setDoubleBuffered(db);
    if (!currentSize.equals(desiredSize)) {
        final double xFactor = desiredSize.width * 1. / currentSize.width;
        final double yFactor = desiredSize.height * 1. / currentSize.height;
        final double factor = Math.min(xFactor, yFactor);
        info("optimal size is (" + currentSize.width + ", " + currentSize.height + ")");
        info("scaling with a factor of " + factor);

        final AffineTransform tx = new AffineTransform();
        tx.scale(factor, factor);
        final AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
        BufferedImage biNew = new BufferedImage((int) (bi.getWidth() * factor), (int) (bi.getHeight() * factor),
                bi.getType());
        bi = op.filter(bi, biNew);
    }
    g.dispose();

    OutputStream os = null;
    try {
        final File file = new File(output, (outputFileName != null ? outputFileName : name) + "." + format);
        os = new FileOutputStream(file);
        if (!ImageIO.write(bi, format, os)) {
            throw new IllegalStateException("can't save picture " + name + "." + format);
        }
        info("Saved " + file.getAbsolutePath());
    } catch (final IOException e) {
        throw new IllegalStateException("can't save the diagram", e);
    } finally {
        if (os != null) {
            try {
                os.flush();
                os.close();
            } catch (final IOException e) {
                // no-op
            }
        }
    }
}

From source file:org.apache.batchee.tools.maven.DiagramMojo.java

private void saveView(final Dimension currentSize, final Dimension desiredSize, final String name,
        final VisualizationViewer<Node, Edge> viewer) throws MojoExecutionException {
    BufferedImage bi = new BufferedImage(currentSize.width, currentSize.height, BufferedImage.TYPE_INT_ARGB);

    final Graphics2D g = bi.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

    final boolean db = viewer.isDoubleBuffered();
    viewer.setDoubleBuffered(false);/* w  ww.ja  va  2s  .co  m*/
    viewer.paint(g);
    viewer.setDoubleBuffered(db);
    if (!currentSize.equals(desiredSize)) {
        final double xFactor = desiredSize.width * 1. / currentSize.width;
        final double yFactor = desiredSize.height * 1. / currentSize.height;
        final double factor = Math.min(xFactor, yFactor);
        getLog().info("optimal size is (" + currentSize.width + ", " + currentSize.height + ")");
        getLog().info("scaling with a factor of " + factor);

        final AffineTransform tx = new AffineTransform();
        tx.scale(factor, factor);
        final AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
        BufferedImage biNew = new BufferedImage((int) (bi.getWidth() * factor), (int) (bi.getHeight() * factor),
                bi.getType());
        bi = op.filter(bi, biNew);
    }
    g.dispose();

    OutputStream os = null;
    try {
        final File file = new File(output, (outputFileName != null ? outputFileName : name) + "." + format);
        os = new FileOutputStream(file);
        if (!ImageIO.write(bi, format, os)) {
            throw new MojoExecutionException("can't save picture " + name + "." + format);
        }
        getLog().info("Saved " + file.getAbsolutePath());
    } catch (final IOException e) {
        throw new MojoExecutionException("can't save the diagram", e);
    } finally {
        if (os != null) {
            try {
                os.flush();
                os.close();
            } catch (final IOException e) {
                // no-op
            }
        }
    }
}

From source file:paintbasico2d.VentanaPrincipal.java

private void jButtonAgrandarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAgrandarActionPerformed
    // TODO add your handling code here:
    VentanaInterna vi = (VentanaInterna) (escritorio.getSelectedFrame());
    if (vi != null) {
        BufferedImage ImgSource = vi.getLienzo().getImage();

        if (ImgSource != null) {
            AffineTransform at = AffineTransform.getScaleInstance(1.25, 1.25);
            try {
                AffineTransformOp atop = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
                BufferedImage imgdest = atop.filter(ImgSource, null);
                vi.getLienzo().setImage(imgdest);
                vi.getLienzo().repaint();
            } catch (Exception e) {
                System.err.println("error");
            }//w  w w .  ja v a 2s. c  o  m
        }
    }
}