Java examples for 2D Graphics:BufferedImage
drop BufferedImage Shadow
import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Polygon; import java.awt.RadialGradientPaint; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.geom.Area; import java.awt.image.BufferedImage; import java.awt.image.ConvolveOp; import java.awt.image.Kernel; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import javax.imageio.ImageIO; import javax.swing.JFrame; import org.apache.log4j.Logger; public class Main{ public static BufferedImage dropShadow(BufferedImage in, int shadowWidth) { // move bottom right // gray the image, // blur it a bit // paint over original BufferedImage result = new BufferedImage(in.getWidth() + shadowWidth, in.getHeight() + shadowWidth, BufferedImage.TYPE_INT_ARGB); Graphics2D g = result.createGraphics(); g.drawImage(in, shadowWidth >> 1, shadowWidth >> 1, null); // g.drawImage(in, 0, 0, null); // now gray out the image, keep alpha int[] pixels = new int[result.getWidth() * result.getHeight()]; result.getRGB(0, 0, result.getWidth(), result.getHeight(), pixels, 0 /*offset*/, result.getWidth() /*scansize */); for (int i = 0; i < pixels.length; i++) { // keep only alpha channel and some grey pixels[i] = (pixels[i] & (0xff000000)) | 0x00505050; }//from w w w .j a va2s . c o m result.setRGB(0, 0, result.getWidth(), result.getHeight(), pixels, 0 /*offset*/, result.getWidth() /*scansize */); g.dispose(); // blur the opaque gray into the transparent surrounding result = getGaussianBlurFilter((int) (shadowWidth * 1.2), true) .filter(result, null); result = getGaussianBlurFilter((int) (shadowWidth * 1.2), false) .filter(result, null); g = result.createGraphics(); g.drawImage(in, 0, 0, null); g.dispose(); return result; } public static ConvolveOp getGaussianBlurFilter(int radius, boolean horizontal) { if (radius < 1) { throw new IllegalArgumentException("Radius must be >= 1"); } int size = radius * 2 + 1; float[] data = new float[size]; float sigma = radius / 3.0f; float twoSigmaSquare = 2.0f * sigma * sigma; float sigmaRoot = (float) Math.sqrt(twoSigmaSquare * Math.PI); float total = 0.0f; for (int i = -radius; i <= radius; i++) { float distance = i * i; int index = i + radius; data[index] = (float) Math.exp(-distance / twoSigmaSquare) / sigmaRoot; total += data[index]; } for (int i = 0; i < data.length; i++) { data[i] /= total; } Kernel kernel = null; if (horizontal) { kernel = new Kernel(size, 1, data); } else { kernel = new Kernel(1, size, data); } return new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); } }