Example usage for java.awt.image ConvolveOp EDGE_ZERO_FILL

List of usage examples for java.awt.image ConvolveOp EDGE_ZERO_FILL

Introduction

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

Prototype

int EDGE_ZERO_FILL

To view the source code for java.awt.image ConvolveOp EDGE_ZERO_FILL.

Click Source Link

Document

Pixels at the edge of the destination image are set to zero.

Usage

From source file:Main.java

/**
 * Applies a gaussian blur of the given radius to the given {@link BufferedImage} using a kernel
 * convolution.//from  w w w. j av a 2s . c o m
 *
 * @param source The source image.
 * @param radius The blur radius, in pixels.
 * @return A new, blurred image, or the source image if no blur is performed.
 */
public static BufferedImage blurredImage(BufferedImage source, double radius) {
    if (radius == 0) {
        return source;
    }

    final int r = (int) Math.ceil(radius);
    final int rows = r * 2 + 1;
    final float[] kernelData = new float[rows * rows];

    final double sigma = radius / 3;
    final double sigma22 = 2 * sigma * sigma;
    final double sqrtPiSigma22 = Math.sqrt(Math.PI * sigma22);
    final double radius2 = radius * radius;

    double total = 0;
    int index = 0;
    double distance2;

    int x, y;
    for (y = -r; y <= r; y++) {
        for (x = -r; x <= r; x++) {
            distance2 = 1.0 * x * x + 1.0 * y * y;
            if (distance2 > radius2) {
                kernelData[index] = 0;
            } else {
                kernelData[index] = (float) (Math.exp(-distance2 / sigma22) / sqrtPiSigma22);
            }
            total += kernelData[index];
            ++index;
        }
    }

    for (index = 0; index < kernelData.length; index++) {
        kernelData[index] /= total;
    }

    // We first pad the image so the kernel can operate at the edges.
    BufferedImage paddedSource = paddedImage(source, r);
    BufferedImage blurredPaddedImage = operatedImage(paddedSource,
            new ConvolveOp(new Kernel(rows, rows, kernelData), ConvolveOp.EDGE_ZERO_FILL, null));
    return blurredPaddedImage.getSubimage(r, r, source.getWidth(), source.getHeight());
}