Example usage for java.awt.image AffineTransformOp filter

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

Introduction

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

Prototype

public final WritableRaster filter(Raster src, WritableRaster dst) 

Source Link

Document

Transforms the source Raster and stores the results in the destination Raster .

Usage

From source file:AppSpringLayout.java

protected BufferedImage mirrorImage(BufferedImage imageToFlip) {

    // Flip the image horizontally
    AffineTransform tx = AffineTransform.getScaleInstance(-1, 1);
    tx.translate(-imageToFlip.getWidth(null), 0);
    AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    imageToFlip = op.filter(imageToFlip, null);

    return imageToFlip;
}

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//  ww  w  .jav a 2  s  . co  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:net.sf.ginp.browser.FolderManagerImpl.java

void makeThumbImage(final File origPicture, final String thumbFileName, final int maxThumbSize) {
    if (log.isDebugEnabled()) {
        log.debug("makeThumbImage: origFileName=" + origPicture.getAbsolutePath() + " thumbFileName="
                + thumbFileName + " maxThumbSize=" + maxThumbSize);
    }//from ww  w .  j  ava  2  s .com

    // Only jpegs supported.
    if ((origPicture.getName().toLowerCase()).endsWith(".jpg")
            || (origPicture.getName().toLowerCase()).endsWith(".jpeg")) {
        try {
            // thumb it.
            JPEGImageDecoder dc = JPEGCodec.createJPEGDecoder((new FileInputStream(origPicture)));
            BufferedImage origImage = dc.decodeAsBufferedImage();
            int origHeight = origImage.getHeight(null);
            int origWidth = origImage.getWidth(null);
            int scaledW = 0;
            int scaledH = 0;
            double scale = 1.0;

            if (origHeight < origWidth) {
                scale = (double) maxThumbSize / (double) origWidth;
            } else {
                scale = (double) maxThumbSize / (double) origHeight;
            }

            scaledW = (int) (scale * origWidth);
            scaledH = (int) (scale * origHeight);

            //AffineTransform  at  = new AffineTransform();
            AffineTransform tx;
            AffineTransformOp af;
            JPEGImageEncoder encoder;
            BufferedImage outImage;

            outImage = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_INT_RGB);
            tx = new AffineTransform();
            tx.scale(scale, scale);
            af = new AffineTransformOp(tx, null);
            af.filter(origImage, outImage);

            File ginpFolder = new File(
                    thumbFileName.substring(0, thumbFileName.lastIndexOf("/.ginp")) + "/.ginp");

            if (!(ginpFolder.exists())) {
                ginpFolder.mkdir();
            }

            encoder = JPEGCodec.createJPEGEncoder(new FileOutputStream(thumbFileName));
            encoder.encode(outImage);
        } catch (Exception e) {
            log.error("Error Makeing Thumb Image " + thumbFileName, e);
        }
    }
}

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 va 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.  j a va 2s.  c  om*/
    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:com.googlecode.jchav.chart.Chart.java

/**
 * Creates a PNG graphic for the given data as a thumbnail image.
 *
 * @param out the stream to write the PNG to.  The caller is responsible
 *  for closing the stream./*from   w  w  w .ja  v  a2  s. com*/
 * 
 * @throws IOException if there was a problem creating the chart.
 */
public void writeThumbnail(final OutputStream out) throws IOException {

    // Set up the transfomration:
    final AffineTransform xform = new AffineTransform();
    xform.scale(thumbnailScale, thumbnailScale);

    // Thanks to the almanac for this one:
    // http://javaalmanac.com/egs/java.awt.image/CreateTxImage.html?l=rel
    final AffineTransformOp op = new AffineTransformOp(xform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);

    // The thumbnail does not need so much chart chrome: you can't
    // read the axis and the title is given in the HTML, so removing
    // these elements means there's more space in the thumbnail for the data
    boolean thumbChrome = false;

    if (false == thumbChrome) {
        chart.setTitle((String) null);
        chart.clearSubtitles();
        chart.removeLegend();

        // Removing the axis completly looks just weird, so we just
        // remove the labels:

        chart.getCategoryPlot().getRangeAxis().setLabel(null);
        chart.getCategoryPlot().getRangeAxis().setTickLabelsVisible(true);
        chart.getCategoryPlot().getRangeAxis().setTickMarksVisible(true);
        chart.getCategoryPlot().getRangeAxis().setAxisLineVisible(true);

        //  To show up at a small scale, we need a good sized axis stroke:
        Stroke stroke = new BasicStroke(2f);
        chart.getCategoryPlot().getRangeAxis().setAxisLineStroke(stroke);
        chart.getCategoryPlot().getRangeAxis().setTickMarkStroke(stroke);

        chart.getCategoryPlot().getDomainAxis().setLabel(null);
        chart.getCategoryPlot().getDomainAxis().setTickLabelsVisible(false);
        chart.getCategoryPlot().getDomainAxis().setAxisLineVisible(true);
        chart.getCategoryPlot().getDomainAxis().setAxisLineStroke(stroke);
    }

    final BufferedImage fullsize = chart.createBufferedImage(width, height);

    Graphics2D g = fullsize.createGraphics();
    for (Decorator decorator : thumbnailDecorators) {
        decorator.decorate(g, this);
    }

    final BufferedImage thumbnail = op.filter(fullsize, null /*null means create the image for us*/);

    ChartUtilities.writeBufferedImageAsPNG(out, thumbnail);

}

From source file:paintbasico2d.VentanaPrincipal.java

private void jButtonAchicarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAchicarActionPerformed
    VentanaInterna vi = (VentanaInterna) (escritorio.getSelectedFrame());
    if (vi != null) {
        BufferedImage ImgSource = vi.getLienzo().getImage();

        if (ImgSource != null) {
            AffineTransform at = AffineTransform.getScaleInstance(0.75, 0.75);
            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 .j a  v  a 2s  .  co m
        }
    } // TODO add your handling code here:
}

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");
            }/*from   w w  w.  j a va2s .  co  m*/
        }
    }
}

From source file:paintbasico2d.VentanaPrincipal.java

private void jButton180gradosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton180gradosActionPerformed
    VentanaInterna vi = (VentanaInterna) (escritorio.getSelectedFrame());
    if (vi != null) {
        BufferedImage ImgSource = vi.getLienzo().getImage();

        if (ImgSource != null) {
            double r = Math.toRadians(180);
            Point p = new Point(ImgSource.getWidth() / 2, ImgSource.getHeight() / 2);
            AffineTransform at = AffineTransform.getRotateInstance(r, p.x, p.y);

            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");
            }//from   ww w.  jav  a  2s.c o  m
        }
    }
}

From source file:paintbasico2d.VentanaPrincipal.java

private void jButton90gradosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton90gradosActionPerformed
    VentanaInterna vi = (VentanaInterna) (escritorio.getSelectedFrame());
    if (vi != null) {
        BufferedImage ImgSource = vi.getLienzo().getImage();

        if (ImgSource != null) {
            double r = Math.toRadians(90);
            Point p = new Point(ImgSource.getWidth() / 2, ImgSource.getHeight() / 2);
            AffineTransform at = AffineTransform.getRotateInstance(r, p.x, p.y);

            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.  j a v a 2s  .  c  o  m
        }
    }
}