blur BufferedImage - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Blur

Description

blur BufferedImage

Demo Code


//package com.java2s;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;

public class Main {

    public static BufferedImage blur(BufferedImage source, int radius) {

        BufferedImage img = new BufferedImage(source.getWidth() + radius
                * 2, source.getHeight() + radius * 2,
                BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g2 = (Graphics2D) img.getGraphics();
        g2.setColor(new Color(0, 0, 0));
        g2.fillRect(0, 0, source.getWidth() + radius * 2,
                source.getHeight() + radius * 2);
        g2.drawImage(source, radius, radius, null);
        g2.dispose();//w w w . ja  va2 s . c  o m

        int square = radius * radius;
        float sum = 0;
        float[] matrix = new float[square];
        for (int i = 0; i < square; i++) {
            int dx = i % radius - radius / 2;
            int dy = i / radius - radius / 2;
            matrix[i] = (float) (radius - Math.sqrt(dx * dx + dy * dy));
            sum += matrix[i];
        }
        for (int i = 0; i < square; i++) {
            matrix[i] /= sum;
        }

        BufferedImageOp op = new ConvolveOp(new Kernel(radius, radius,
                matrix), ConvolveOp.EDGE_ZERO_FILL, null);

        BufferedImage res = op.filter(img, null);

        BufferedImage out = new BufferedImage(source.getWidth(),
                source.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);

        Graphics2D g3 = (Graphics2D) out.getGraphics();
        g3.drawImage(res, -radius, -radius, null);
        g3.dispose();
        return out;

    }
}

Related Tutorials