Example usage for java.awt.image AffineTransformOp AffineTransformOp

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

Introduction

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

Prototype

public AffineTransformOp(AffineTransform xform, int interpolationType) 

Source Link

Document

Constructs an AffineTransformOp given an affine transform and the interpolation type.

Usage

From source file:ImageOps.java

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    int w = getSize().width;
    int h = getSize().height;

    g2.setColor(Color.black);//from w w w  .j a va 2  s.  co  m
    float[][] data = { { 0.1f, 0.1f, 0.1f, // low-pass filter
            0.1f, 0.2f, 0.1f, 0.1f, 0.1f, 0.1f }, SHARPEN3x3_3 };

    String theDesc[] = { "Convolve LowPass", "Convolve Sharpen", "LookupOp", "RescaleOp" };
    for (int i = 0; i < bi.length; i++) {
        int iw = bi[i].getWidth(this);
        int ih = bi[i].getHeight(this);
        int x = 0, y = 0;

        AffineTransform at = new AffineTransform();
        at.scale((w - 14) / 2.0 / iw, (h - 34) / 2.0 / ih);

        BufferedImageOp biop = null;
        BufferedImage bimg = new BufferedImage(iw, ih, BufferedImage.TYPE_INT_RGB);

        switch (i) {
        case 0:
        case 1:
            x = i == 0 ? 5 : w / 2 + 3;
            y = 15;
            Kernel kernel = new Kernel(3, 3, data[i]);
            ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
            cop.filter(bi[i], bimg);
            biop = new AffineTransformOp(at, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
            break;
        case 2:
            x = 5;
            y = h / 2 + 15;
            byte chlut[] = new byte[256];
            for (int j = 0; j < 200; j++)
                chlut[j] = (byte) (256 - j);
            ByteLookupTable blut = new ByteLookupTable(0, chlut);
            LookupOp lop = new LookupOp(blut, null);
            lop.filter(bi[i], bimg);
            biop = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
            break;
        case 3:
            x = w / 2 + 3;
            y = h / 2 + 15;
            RescaleOp rop = new RescaleOp(1.1f, 20.0f, null);
            rop.filter(bi[i], bimg);
            biop = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
        }
        g2.drawImage(bimg, biop, x, y);
        TextLayout tl = new TextLayout(theDesc[i], g2.getFont(), g2.getFontRenderContext());
        tl.draw(g2, (float) x, (float) y - 4);
    }
}

From source file:ImageDrawingComponent.java

public void paint(Graphics g) {

    Graphics2D g2 = (Graphics2D) g;

    switch (opIndex) {
    case 0: /* copy */
        g.drawImage(bi, 0, 0, null);//from www . ja  v a2 s  . co m
        break;

    case 1: /* scale up using coordinates */
        g.drawImage(bi, 0, 0, w, h, /* dst rectangle */
                0, 0, w / 2, h / 2, /* src area of image */
                null);
        break;

    case 2: /* scale down using transform */
        g2.drawImage(bi, AffineTransform.getScaleInstance(0.7, 0.7), null);
        break;

    case 3: /* scale up using transform Op and BICUBIC interpolation */
        AffineTransform at = AffineTransform.getScaleInstance(1.5, 1.5);
        AffineTransformOp aop = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
        g2.drawImage(bi, aop, 0, 0);
        break;

    case 4: /* low pass filter */
    case 5: /* sharpen */
        float[] data = (opIndex == 4) ? BLUR3x3 : SHARPEN3x3;
        ConvolveOp cop = new ConvolveOp(new Kernel(3, 3, data), ConvolveOp.EDGE_NO_OP, null);
        g2.drawImage(bi, cop, 0, 0);
        break;

    case 6: /* rescale */
        RescaleOp rop = new RescaleOp(1.1f, 20.0f, null);
        g2.drawImage(bi, rop, 0, 0);
        break;

    case 7: /* lookup */
        byte lut[] = new byte[256];
        for (int j = 0; j < 256; j++) {
            lut[j] = (byte) (256 - j);
        }
        ByteLookupTable blut = new ByteLookupTable(0, lut);
        LookupOp lop = new LookupOp(blut, null);
        g2.drawImage(bi, lop, 0, 0);
        break;

    default:
    }
}

From source file:AffineTransformApp.java

public void applyFilter() {
    AffineTransformOp op = new AffineTransformOp(transform, null);
    Graphics2D biDestG2D = biDest.createGraphics();
    biDestG2D.clearRect(0, 0, biDest.getWidth(this), biDest.getHeight(this));
    op.filter(biSrc, biDest);//from  w w  w  .j  a  v  a 2  s. c o m
    bi = biDest;
}

From source file:org.apache.hadoop.chukwa.hicc.ImageSlicer.java

public BufferedImage tile(BufferedImage image, int level, XYData quadrant, XYData size, boolean efficient)
        throws Exception {
    double scale = Math.pow(2, level);
    if (efficient) {
        /* efficient: crop out the area of interest first, then scale and copy it */
        XYData inverSize = new XYData((int) (image.getWidth(null) / (size.getX() * scale)),
                (int) (image.getHeight(null) / (size.getY() * scale)));
        XYData topLeft = new XYData(quadrant.getX() * size.getX() * inverSize.getX(),
                quadrant.getY() * size.getY() * inverSize.getY());
        XYData newSize = new XYData((size.getX() * inverSize.getX()), (size.getY() * inverSize.getY()));
        if (inverSize.getX() < 1.0 || inverSize.getY() < 1.0) {
            throw new Exception("Requested zoom level (" + level + ") is too high.");
        }/*w w w.  j ava2s .c  o  m*/
        image = image.getSubimage(topLeft.getX(), topLeft.getY(), newSize.getX(), newSize.getY());
        BufferedImage zoomed = new BufferedImage(size.getX(), size.getY(), BufferedImage.TYPE_INT_RGB);
        zoomed.getGraphics().drawImage(image, 0, 0, size.getX(), size.getY(), null);
        if (level > maxLevel) {
            maxLevel = level;
        }
        return zoomed;
    } else {
        /* inefficient: copy the whole image, scale it and then crop out the area of interest */
        XYData newSize = new XYData((int) (size.getX() * scale), (int) (size.getY() * scale));
        XYData topLeft = new XYData(quadrant.getX() * size.getX(), quadrant.getY() * size.getY());
        if (newSize.getX() > image.getWidth(null) || newSize.getY() > image.getHeight(null)) {
            throw new Exception("Requested zoom level (" + level + ") is too high.");
        }
        AffineTransform tx = new AffineTransform();
        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
        tx.scale(scale, scale);
        image = op.filter(image, null);
        BufferedImage zoomed = image.getSubimage(topLeft.getX(), topLeft.getY(), newSize.getX(),
                newSize.getY());
        if (level > maxLevel) {
            maxLevel = level;
        }
        return zoomed;
    }
}

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 w  w  .j a  va 2 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:ImageProcessingTest.java

public ImageProcessingFrame() {
    setTitle("ImageProcessingTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    add(new JComponent() {
        public void paintComponent(Graphics g) {
            if (image != null)
                g.drawImage(image, 0, 0, null);
        }/*from w ww . ja v  a2  s . c  o  m*/
    });

    JMenu fileMenu = new JMenu("File");
    JMenuItem openItem = new JMenuItem("Open");
    openItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            openFile();
        }
    });
    fileMenu.add(openItem);

    JMenuItem exitItem = new JMenuItem("Exit");
    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            System.exit(0);
        }
    });
    fileMenu.add(exitItem);

    JMenu editMenu = new JMenu("Edit");
    JMenuItem blurItem = new JMenuItem("Blur");
    blurItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            float weight = 1.0f / 9.0f;
            float[] elements = new float[9];
            for (int i = 0; i < 9; i++)
                elements[i] = weight;
            convolve(elements);
        }
    });
    editMenu.add(blurItem);

    JMenuItem sharpenItem = new JMenuItem("Sharpen");
    sharpenItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            float[] elements = { 0.0f, -1.0f, 0.0f, -1.0f, 5.f, -1.0f, 0.0f, -1.0f, 0.0f };
            convolve(elements);
        }
    });
    editMenu.add(sharpenItem);

    JMenuItem brightenItem = new JMenuItem("Brighten");
    brightenItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            float a = 1.1f;
            // float b = 20.0f;
            float b = 0;
            RescaleOp op = new RescaleOp(a, b, null);
            filter(op);
        }
    });
    editMenu.add(brightenItem);

    JMenuItem edgeDetectItem = new JMenuItem("Edge detect");
    edgeDetectItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            float[] elements = { 0.0f, -1.0f, 0.0f, -1.0f, 4.f, -1.0f, 0.0f, -1.0f, 0.0f };
            convolve(elements);
        }
    });
    editMenu.add(edgeDetectItem);

    JMenuItem negativeItem = new JMenuItem("Negative");
    negativeItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            short[] negative = new short[256 * 1];
            for (int i = 0; i < 256; i++)
                negative[i] = (short) (255 - i);
            ShortLookupTable table = new ShortLookupTable(0, negative);
            LookupOp op = new LookupOp(table, null);
            filter(op);
        }
    });
    editMenu.add(negativeItem);

    JMenuItem rotateItem = new JMenuItem("Rotate");
    rotateItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            if (image == null)
                return;
            AffineTransform transform = AffineTransform.getRotateInstance(Math.toRadians(5),
                    image.getWidth() / 2, image.getHeight() / 2);
            AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BICUBIC);
            filter(op);
        }
    });
    editMenu.add(rotateItem);

    JMenuBar menuBar = new JMenuBar();
    menuBar.add(fileMenu);
    menuBar.add(editMenu);
    setJMenuBar(menuBar);
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploadThumbnailer.java

private BufferedImage scaleImage(BufferedImage image, float scaleFactor) {
    AffineTransform transform = AffineTransform.getScaleInstance(scaleFactor, scaleFactor);
    AffineTransformOp atoOp = new AffineTransformOp(transform, null);
    return atoOp.filter(image, null);
}

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:net.sf.ginp.util.GinpUtil.java

/**
 * Take a jpeg from an input stream and write it to an output.
 * stream with a scaled width and height
 * @param sos output stream for image//from   w w  w .j  av  a2 s  . c  o  m
 * @param is input stream for image
 * @param width width
 * @param height height
 * @throws IOException if there is an error writing or reading
 */
public static void writeScaledImageToStream(final OutputStream sos, final InputStream is, final int width,
        final int height) throws IOException {
    JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(is);
    BufferedImage origImage = decoder.decodeAsBufferedImage();
    int origHeight = origImage.getHeight(null);
    int origWidth = origImage.getWidth(null);
    int scaledW = 0;
    int scaledH = 0;
    double scaleW = 1.0;
    double scaleH = 1.0;

    // close input stream
    is.close();

    // Calculate scale factors
    if (width == 0) {
        scaleW = (double) height / (double) origHeight;
        scaleH = (double) height / (double) origHeight;
    } else if (height == 0) {
        scaleW = (double) width / (double) origWidth;
        scaleH = (double) width / (double) origWidth;
    } else {
        scaleW = (double) width / (double) origWidth;
        scaleH = (double) height / (double) origHeight;
    }

    scaledW = (int) (scaleW * origWidth);
    scaledH = (int) (scaleH * origHeight);

    BufferedImage outImage = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_INT_RGB);
    AffineTransform tx = new AffineTransform();

    tx.scale(scaleW, scaleH);

    AffineTransformOp af = new AffineTransformOp(tx, null);

    af.filter(origImage, outImage);

    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);

    encoder.encode(outImage);
}

From source file:com.xuggle.xuggler.UtilsTest.java

@SuppressWarnings("deprecation")
@Test//from  w  w  w  .  j  a v  a  2  s . c o m
public void testPictureToPictureWithRotate() {
    // note that the image is square in this test to make rotation
    // easier to handle

    int size = 50;
    int black = Color.BLACK.getRGB();
    int white = Color.WHITE.getRGB();

    // construct an image with black and white stripped columns

    BufferedImage image1 = new BufferedImage(size, size, BufferedImage.TYPE_3BYTE_BGR);
    for (int x = 0; x < size; ++x)
        for (int y = 0; y < size; ++y) {
            int color = x % 2 == 0 ? black : white;
            image1.setRGB(x, y, color);
        }

    // convert image1 to a picture and then back to image2

    BufferedImage image2 = Utils.videoPictureToImage(Utils.imageToVideoPicture(image1, 0));

    // rotae image2

    AffineTransform t = AffineTransform.getRotateInstance(Math.PI / 2, image2.getWidth() / 2,
            image2.getHeight() / 2);
    AffineTransformOp ato = new AffineTransformOp(t, AffineTransformOp.TYPE_BICUBIC);
    BufferedImage image3 = new BufferedImage(size, size, BufferedImage.TYPE_3BYTE_BGR);
    ato.filter(image2, image3);

    // convert image2 to a picture and then back to image3

    BufferedImage image4 = Utils.videoPictureToImage(Utils.imageToVideoPicture(image3, 0));

    // test that image4 now contains stripped rows (not columns)

    for (int x = 0; x < size; ++x)
        for (int y = 0; y < size; ++y) {
            int pixel = image4.getRGB(x, y);
            int color = y % 2 == 0 ? black : white;
            assertTrue("color value missmatch", pixel == color);
        }
}