Java blur Image

Prashant Thorat picture Prashant Thorat · Mar 27, 2015 · Viewed 17.6k times · Source

I am trying to blur the image

   int radius = 11;
    int size = radius * 2 + 1;
    float weight = 1.0f / (size * size);
    float[] data = new float[size * size];

    for (int i = 0; i < data.length; i++) {
        data[i] = weight;
    }

    Kernel kernel = new Kernel(size, size, data);
    ConvolveOp op = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
    //tbi is BufferedImage
    BufferedImage i = op.filter(tbi, null);

It will blur the image but not all portion of the image.

enter image description here

Where I am missing so that it will blur complete image. Without any path .

Answer

haraldK picture haraldK · Oct 28, 2015

The standard Java ConvolveOp only has the two options EDGE_ZERO_FILL and EDGE_NO_OP. What you want is the options from the JAI equivalent (ConvolveDescriptor), which is EDGE_REFLECT (or EDGE_WRAP, if you want repeating patterns).

If you don't want to use JAI, you can implement this yourself, by copying your image to a larger image, stretching or wrapping the edges, apply the convolve op, then cut off the edges (similar to the technique described in the "Working on the Edge" section of the article posted by @halex in the comments section, but according to that article, you can also just leave the edges transparent).

For simplicity, you can just use my implementation called ConvolveWithEdgeOp which does the above (BSD license).

The code will be similar to what you had originally:

// ...kernel setup as before...
Kernel kernel = new Kernel(size, size, data);
BufferedImageOp op = new ConvolveWithEdgeOp(kernel, ConvolveOp.EDGE_REFLECT, null);

BufferedImage blurred = op.filter(original, null);

The filter should work like any other BufferedImageOp, and should work with any BufferedImage.