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:se.trixon.almond.GraphicsHelper.java

public static BufferedImage flipBufferedImageY(BufferedImage bufferedImage) {
    AffineTransform affineTransform = AffineTransform.getScaleInstance(1, -1);
    affineTransform.translate(-bufferedImage.getWidth(null), 0);
    AffineTransformOp affineTransformOp = new AffineTransformOp(affineTransform,
            AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    return affineTransformOp.filter(bufferedImage, null);
}

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//  w  w w  .j  a  v  a 2 s  . com
 * @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:de.mfo.jsurf.grid.RotationGrid.java

public static void saveToPNG(OutputStream os, BufferedImage bufferedImage) throws java.io.IOException {
    AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
    tx.translate(0, -bufferedImage.getHeight(null));
    AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    bufferedImage = op.filter(bufferedImage, null);
    javax.imageio.ImageIO.write(bufferedImage, "png", os);
}

From source file:com.mikenimer.familydam.services.photos.ThumbnailService.java

/**
 * using the metadata orientation transformation information rotate the image.
 * @param image/*from   w w w  .  ja  v  a2 s . c  om*/
 * @param transform
 * @return
 * @throws Exception
 */
public static BufferedImage transformImage(BufferedImage image, AffineTransform transform) throws Exception {

    AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BICUBIC);

    BufferedImage destinationImage = op.createCompatibleDestImage(image,
            (image.getType() == BufferedImage.TYPE_BYTE_GRAY) ? image.getColorModel() : null);
    Graphics2D g = destinationImage.createGraphics();
    g.setBackground(Color.WHITE);
    g.clearRect(0, 0, destinationImage.getWidth(), destinationImage.getHeight());
    destinationImage = op.filter(image, destinationImage);
    return destinationImage;
}

From source file:com.aimluck.eip.fileupload.util.FileuploadUtils.java

public static BufferedImage transformImage(BufferedImage image, AffineTransform transform, int newWidth,
        int newHeight) throws Exception {

    AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BICUBIC);

    BufferedImage destinationImage = new BufferedImage(newWidth, newHeight, image.getType());
    Graphics2D g = destinationImage.createGraphics();
    g.setColor(Color.WHITE);//from   w  ww.j  a v a 2 s .  co m

    destinationImage = op.filter(image, destinationImage);

    return destinationImage;
}

From source file:edu.umn.cs.spatialHadoop.operations.HeatMapPlot.java

private static <S extends Shape> void plotHeatMapLocal(Path inFile, Path outFile, OperationsParams params)
        throws IOException {
    int imageWidth = params.getInt("width", 1000);
    int imageHeight = params.getInt("height", 1000);

    Shape shape = params.getShape("shape", new Point());
    Shape plotRange = params.getShape("rect", null);

    boolean keepAspectRatio = params.is("keep-ratio", true);

    InputSplit[] splits;/*from  w w  w .  j a  va 2s . co  m*/
    FileSystem inFs = inFile.getFileSystem(params);
    FileStatus inFStatus = inFs.getFileStatus(inFile);
    if (inFStatus != null && !inFStatus.isDir()) {
        // One file, retrieve it immediately.
        // This is useful if the input is a hidden file which is automatically
        // skipped by FileInputFormat. We need to plot a hidden file for the case
        // of plotting partition boundaries of a spatial index
        splits = new InputSplit[] { new FileSplit(inFile, 0, inFStatus.getLen(), new String[0]) };
    } else {
        JobConf job = new JobConf(params);
        ShapeInputFormat<Shape> inputFormat = new ShapeInputFormat<Shape>();
        ShapeInputFormat.addInputPath(job, inFile);
        splits = inputFormat.getSplits(job, 1);
    }

    boolean vflip = params.is("vflip");

    Rectangle fileMBR;
    if (plotRange != null) {
        fileMBR = plotRange.getMBR();
    } else {
        fileMBR = FileMBR.fileMBR(inFile, params);
    }

    if (keepAspectRatio) {
        // Adjust width and height to maintain aspect ratio
        if (fileMBR.getWidth() / fileMBR.getHeight() > (double) imageWidth / imageHeight) {
            // Fix width and change height
            imageHeight = (int) (fileMBR.getHeight() * imageWidth / fileMBR.getWidth());
        } else {
            imageWidth = (int) (fileMBR.getWidth() * imageHeight / fileMBR.getHeight());
        }
    }

    // Create the frequency map
    int radius = params.getInt("radius", 5);
    FrequencyMap frequencyMap = new FrequencyMap(imageWidth, imageHeight);

    for (InputSplit split : splits) {
        ShapeRecordReader<Shape> reader = new ShapeRecordReader<Shape>(params, (FileSplit) split);
        Rectangle cell = reader.createKey();
        while (reader.next(cell, shape)) {
            Rectangle shapeBuffer = shape.getMBR();
            if (shapeBuffer == null)
                continue;
            shapeBuffer = shapeBuffer.buffer(radius, radius);
            if (plotRange == null || shapeBuffer.isIntersected(plotRange)) {
                Point centerPoint = shapeBuffer.getCenterPoint();
                int cx = (int) Math.round((centerPoint.x - fileMBR.x1) * imageWidth / fileMBR.getWidth());
                int cy = (int) Math.round((centerPoint.y - fileMBR.y1) * imageHeight / fileMBR.getHeight());
                frequencyMap.addPoint(cx, cy, radius);
            }
        }
        reader.close();
    }

    // Convert frequency map to an image with colors
    NASAPoint.setColor1(params.getColor("color1", Color.BLUE));
    NASAPoint.setColor2(params.getColor("color2", Color.RED));
    NASAPoint.gradientType = params.getGradientType("gradient", NASAPoint.GradientType.GT_HUE);
    String valueRangeStr = params.get("valuerange");
    MinMax valueRange = null;
    if (valueRangeStr != null) {
        String[] parts = valueRangeStr.contains("..") ? valueRangeStr.split("\\.\\.", 2)
                : valueRangeStr.split(",", 2);
        valueRange = new MinMax(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
    }

    boolean skipZeros = params.getBoolean("skipzeros", false);
    BufferedImage image = frequencyMap.toImage(valueRange, skipZeros);

    if (vflip) {
        AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
        tx.translate(0, -image.getHeight());
        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
        image = op.filter(image, null);
    }
    FileSystem outFs = outFile.getFileSystem(params);
    OutputStream out = outFs.create(outFile, true);
    ImageIO.write(image, "png", out);
    out.close();

}

From source file:ImageFlip.java

public void paint(Graphics g) {
    Image myImage = new ImageIcon("yourImage.jpg").getImage();
    BufferedImage bufferedImage = new BufferedImage(myImage.getWidth(null), myImage.getHeight(null),
            BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = (Graphics2D) g;

    Graphics gb = bufferedImage.getGraphics();
    gb.drawImage(myImage, 0, 0, null);/*from   ww w .  j a v  a 2 s . co  m*/
    gb.dispose();

    AffineTransform tx = AffineTransform.getScaleInstance(-1, 1);
    tx.translate(-myImage.getWidth(null), 0);
    AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    bufferedImage = op.filter(bufferedImage, null);

    g2d.drawImage(myImage, 10, 10, null);
    g2d.drawImage(bufferedImage, null, 300, 10);
}

From source file:edu.umn.cs.spatialHadoop.operations.PyramidPlot.java

private static void plotLocal(Path inFile, Path outFile, OperationsParams params) throws IOException {
    int tileWidth = params.getInt("tilewidth", 256);
    int tileHeight = params.getInt("tileheight", 256);

    Color strokeColor = params.getColor("color", Color.BLACK);

    String hdfDataset = (String) params.get("dataset");
    Shape shape = hdfDataset != null ? new NASARectangle() : (Shape) params.getShape("shape", null);
    Shape plotRange = params.getShape("rect", null);

    String valueRangeStr = (String) params.get("valuerange");
    MinMax valueRange;/*from   w  ww  .j  a  va2  s .co  m*/
    if (valueRangeStr == null) {
        valueRange = null;
    } else {
        String[] parts = valueRangeStr.split(",");
        valueRange = new MinMax(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
    }

    InputSplit[] splits;
    FileSystem inFs = inFile.getFileSystem(params);
    FileStatus inFStatus = inFs.getFileStatus(inFile);
    if (inFStatus != null && !inFStatus.isDir()) {
        // One file, retrieve it immediately.
        // This is useful if the input is a hidden file which is automatically
        // skipped by FileInputFormat. We need to plot a hidden file for the case
        // of plotting partition boundaries of a spatial index
        splits = new InputSplit[] { new FileSplit(inFile, 0, inFStatus.getLen(), new String[0]) };
    } else {
        JobConf job = new JobConf(params);
        ShapeInputFormat<Shape> inputFormat = new ShapeInputFormat<Shape>();
        ShapeInputFormat.addInputPath(job, inFile);
        splits = inputFormat.getSplits(job, 1);
    }

    boolean vflip = params.is("vflip");

    Rectangle fileMBR;
    if (plotRange != null) {
        fileMBR = plotRange.getMBR();
    } else if (hdfDataset != null) {
        // Plotting a NASA file
        fileMBR = new Rectangle(-180, -90, 180, 90);
    } else {
        fileMBR = FileMBR.fileMBR(inFile, params);
    }

    boolean keepAspectRatio = params.is("keep-ratio", true);
    if (keepAspectRatio) {
        // Adjust width and height to maintain aspect ratio
        if (fileMBR.getWidth() > fileMBR.getHeight()) {
            fileMBR.y1 -= (fileMBR.getWidth() - fileMBR.getHeight()) / 2;
            fileMBR.y2 = fileMBR.y1 + fileMBR.getWidth();
        } else {
            fileMBR.x1 -= (fileMBR.getHeight() - fileMBR.getWidth() / 2);
            fileMBR.x2 = fileMBR.x1 + fileMBR.getHeight();
        }
    }

    if (hdfDataset != null) {
        // Collects some stats about the HDF file
        if (valueRange == null)
            valueRange = Aggregate.aggregate(new Path[] { inFile }, params);
        NASAPoint.minValue = valueRange.minValue;
        NASAPoint.maxValue = valueRange.maxValue;
        NASAPoint.setColor1(params.getColor("color1", Color.BLUE));
        NASAPoint.setColor2(params.getColor("color2", Color.RED));
        NASAPoint.gradientType = params.getGradientType("gradient", NASAPoint.GradientType.GT_HUE);
    }

    boolean adaptiveSampling = params.getBoolean("sample", false);

    int numLevels = params.getInt("numlevels", 7);

    float[] levelProb = new float[numLevels];
    double[] scale2 = new double[numLevels];
    double[] scale = new double[numLevels];
    levelProb[0] = params.getFloat(GeometricPlot.AdaptiveSampleRatio, 0.1f);
    // Size of the whole file in pixels at the f

    scale2[0] = (double) tileWidth * tileHeight / (fileMBR.getWidth() * fileMBR.getHeight());
    scale[0] = Math.sqrt(scale2[0]);
    for (int level = 1; level < numLevels; level++) {
        levelProb[level] = levelProb[level - 1] * 4;
        scale2[level] = scale2[level - 1] * (1 << level) * (1 << level);
        scale[level] = scale[level - 1] * (1 << level);
    }

    Map<TileIndex, BufferedImage> tileImages = new HashMap<PyramidPlot.TileIndex, BufferedImage>();

    Map<TileIndex, Graphics2D> tileGraphics = new HashMap<PyramidPlot.TileIndex, Graphics2D>();

    GridInfo bottomGrid = new GridInfo(fileMBR.x1, fileMBR.y1, fileMBR.x2, fileMBR.y2);
    bottomGrid.rows = bottomGrid.columns = (int) Math.round(Math.pow(2, numLevels - 1));

    TileIndex tileIndex = new TileIndex();
    boolean gradualFade = !(shape instanceof Point) && params.getBoolean("fade", false);

    for (InputSplit split : splits) {
        ShapeRecordReader<Shape> reader = new ShapeRecordReader<Shape>(params, (FileSplit) split);
        Rectangle cell = reader.createKey();
        while (reader.next(cell, shape)) {
            Rectangle shapeMBR = shape.getMBR();
            if (shapeMBR != null) {
                int min_level = 0;

                if (adaptiveSampling) {
                    // Special handling for NASA data
                    double p = Math.random();
                    // Skip levels that do not satisfy the probability
                    while (min_level < numLevels && p > levelProb[min_level])
                        min_level++;
                }

                java.awt.Rectangle overlappingCells = bottomGrid.getOverlappingCells(shapeMBR);
                for (tileIndex.level = numLevels - 1; tileIndex.level >= min_level; tileIndex.level--) {
                    if (gradualFade && !(shape instanceof Point)) {
                        double areaInPixels = (shapeMBR.getWidth() + shapeMBR.getHeight())
                                * scale[tileIndex.level];
                        if (areaInPixels < 1.0 && Math.round(areaInPixels * 255) < 1.0) {
                            // This shape can be safely skipped as it is too small to be plotted
                            return;
                        }
                    }

                    for (int i = 0; i < overlappingCells.width; i++) {
                        tileIndex.x = i + overlappingCells.x;
                        for (int j = 0; j < overlappingCells.height; j++) {
                            tileIndex.y = j + overlappingCells.y;
                            // Draw in image associated with this tile
                            Graphics2D g;
                            {
                                g = tileGraphics.get(tileIndex);
                                if (g == null) {
                                    TileIndex key = tileIndex.clone();
                                    BufferedImage image = new BufferedImage(tileWidth, tileHeight,
                                            BufferedImage.TYPE_INT_ARGB);
                                    if (tileImages.put(key, image) != null)
                                        throw new RuntimeException(
                                                "Error! Image is already there but graphics is not "
                                                        + tileIndex);

                                    Color bg_color = new Color(0, 0, 0, 0);

                                    try {
                                        g = image.createGraphics();
                                    } catch (Throwable e) {
                                        g = new SimpleGraphics(image);
                                    }
                                    g.setBackground(bg_color);
                                    g.clearRect(0, 0, tileWidth, tileHeight);
                                    g.setColor(strokeColor);
                                    // Coordinates of this tile in image coordinates
                                    g.translate(-(tileWidth * tileIndex.x), -(tileHeight * tileIndex.y));

                                    tileGraphics.put(key, g);
                                }
                            }

                            shape.draw(g, fileMBR, tileWidth * (1 << tileIndex.level),
                                    tileHeight * (1 << tileIndex.level), scale2[tileIndex.level]);
                        }
                    }
                    // Shrink overlapping cells to match the upper level
                    int updatedX1 = overlappingCells.x / 2;
                    int updatedY1 = overlappingCells.y / 2;
                    int updatedX2 = (overlappingCells.x + overlappingCells.width - 1) / 2;
                    int updatedY2 = (overlappingCells.y + overlappingCells.height - 1) / 2;
                    overlappingCells.x = updatedX1;
                    overlappingCells.y = updatedY1;
                    overlappingCells.width = updatedX2 - updatedX1 + 1;
                    overlappingCells.height = updatedY2 - updatedY1 + 1;
                }
            }
        }
        reader.close();
    }
    // Write image to output
    for (Map.Entry<TileIndex, Graphics2D> tileGraph : tileGraphics.entrySet()) {
        tileGraph.getValue().dispose();
    }
    FileSystem outFS = outFile.getFileSystem(params);
    for (Map.Entry<TileIndex, BufferedImage> tileImage : tileImages.entrySet()) {
        tileIndex = tileImage.getKey();
        BufferedImage image = tileImage.getValue();
        if (vflip) {
            AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
            tx.translate(0, -image.getHeight());
            AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
            image = op.filter(image, null);
            tileIndex.y = ((1 << tileIndex.level) - 1) - tileIndex.y;
        }
        Path imagePath = new Path(outFile, tileIndex.getImageFileName());
        FSDataOutputStream outStream = outFS.create(imagePath);
        ImageIO.write(image, "png", outStream);
        outStream.close();
    }
}

From source file:org.github.jipsg.sanselan.BaseSanselanTest.java

/**
 * Some quick and dirty image scaling - please note that for best performance
 * and quality you should use image rescaling libraries.
 *///from   w  w  w  .  j a  va 2  s  .co  m
@Override
public BufferedImage resample(BufferedImage bufferedImage, int width, int height) {

    Dimension imageDimension = new Dimension(bufferedImage.getWidth(), bufferedImage.getHeight());
    Dimension boundaryDimension = new Dimension(width, height);
    Dimension scaledDimension = BufferedImageUtils.getScaledDimension(imageDimension, boundaryDimension);

    double scaleX = scaledDimension.getWidth() / bufferedImage.getWidth();
    double scaleY = scaledDimension.getHeight() / bufferedImage.getHeight();

    AffineTransform scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
    AffineTransformOp biLinearScaleOp = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_BILINEAR);

    return biLinearScaleOp.filter(bufferedImage,
            new BufferedImage(scaledDimension.width, scaledDimension.height, bufferedImage.getType()));
}

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);
}