Example usage for java.awt.image AffineTransformOp TYPE_NEAREST_NEIGHBOR

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

Introduction

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

Prototype

int TYPE_NEAREST_NEIGHBOR

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

Click Source Link

Document

Nearest-neighbor interpolation type.

Usage

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

/**
 * Flip the image horizontal//www .ja v  a2 s  .  com
 *
 * @param bufferedImage original image
 * @return horizontally flipped image
 */
private static BufferedImage flipHorizontal(BufferedImage bufferedImage) {
    AffineTransform at = AffineTransform.getTranslateInstance(bufferedImage.getWidth(), 0);
    at.scale(-1.0, 1.0);
    BufferedImageOp biOp = new AffineTransformOp(at, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    BufferedImage imgRes = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(),
            bufferedImage.getType());
    return biOp.filter(bufferedImage, imgRes);
}

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

/**
 * Flip the image horizontal//from   w ww  .  j  a v a  2  s  .com
 *
 * @param bufferedImage original image
 * @return horizontally flipped image
 */
private static BufferedImage flipVertical(BufferedImage bufferedImage) {
    AffineTransform at = AffineTransform.getTranslateInstance(0, bufferedImage.getHeight());
    at.scale(1.0, -1.0);
    BufferedImageOp biOp = new AffineTransformOp(at, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    BufferedImage imgRes = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(),
            bufferedImage.getType());
    return biOp.filter(bufferedImage, imgRes);
}

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  v a2s  . c  om
    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: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: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 ww w. ja va  2 s  .  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:edu.umn.cs.spatialHadoop.operations.GeometricPlot.java

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

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

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

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

    String valueRangeStr = (String) params.get("valuerange");
    MinMax valueRange;/*from   w  w  w  .ja  va2  s. c  o 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);
    }

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

    boolean adaptiveSample = shape instanceof Point && params.getBoolean("sample", false);
    float adaptiveSampleRatio = 0.0f;
    if (adaptiveSample) {
        // Calculate the sample ratio
        long recordCount = FileMBR.fileMBR(inFile, params).recordCount;
        adaptiveSampleRatio = params.getFloat(AdaptiveSampleFactor, 1.0f) * width * height / recordCount;
    }

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

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

    double scale2 = (double) width * height / (fileMbr.getWidth() * fileMbr.getHeight());
    double scale = Math.sqrt(scale2);

    // Create an image
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    Color bg_color = params.getColor("bgcolor", new Color(0, 0, 0, 0));
    graphics.setBackground(bg_color);
    graphics.clearRect(0, 0, width, height);
    graphics.setColor(strokeColor);

    for (InputSplit split : splits) {
        if (hdfDataset != null) {
            // Read points from the HDF file
            RecordReader<NASADataset, NASAShape> reader = new HDFRecordReader(params, (FileSplit) split,
                    hdfDataset, true);
            NASADataset dataset = reader.createKey();

            while (reader.next(dataset, (NASAShape) shape)) {
                // Skip with a fixed ratio if adaptive sample is set
                if (adaptiveSample && Math.random() > adaptiveSampleRatio)
                    continue;
                if (plotRange == null || shape.isIntersected(shape)) {
                    shape.draw(graphics, fileMbr, width, height, 0.0);
                }
            }
            reader.close();
        } else {
            RecordReader<Rectangle, Shape> reader = new ShapeRecordReader<Shape>(params, (FileSplit) split);
            Rectangle cell = reader.createKey();
            while (reader.next(cell, shape)) {
                // Skip with a fixed ratio if adaptive sample is set
                if (adaptiveSample && Math.random() > adaptiveSampleRatio)
                    continue;
                Rectangle shapeMBR = shape.getMBR();
                if (shapeMBR != null) {
                    if (plotRange == null || shapeMBR.isIntersected(plotRange)) {
                        if (gradualFade) {
                            double sizeInPixels = (shapeMBR.getWidth() + shapeMBR.getHeight()) * scale;
                            if (sizeInPixels < 1.0 && Math.round(sizeInPixels * 255) < 1.0) {
                                // This shape can be safely skipped as it is too small to be plotted
                                continue;
                            } else {
                                int alpha = (int) Math.round(sizeInPixels * 255);
                                graphics.setColor(new Color((alpha << 24) | color, true));
                            }
                        }
                        shape.draw(graphics, fileMbr, width, height, scale2);
                    }
                }
            }
            reader.close();
        }
    }
    // Write image to output
    graphics.dispose();
    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:pl.edu.icm.visnow.lib.utils.ImageUtilities.java

public static BufferedImage switchAxes(BufferedImage img) {
    if (img == null) {
        return null;
    }/*from  w w w  .ja  v a 2  s  .co  m*/

    return rotateImage(flipImageHorizontal(img), -90, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
}

From source file:se.trixon.almond.GraphicsHelper.java

public static BufferedImage flipBufferedImageX(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: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);
}