Java Graphics How to - Apply stroke to an image with TexturePaint








Question

We would like to know how to apply stroke to an image with TexturePaint.

Answer

import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.TexturePaint;
import java.awt.image.BufferedImage;
import java.net.URL;
//w w  w. ja  v  a2s  .  c  om
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class Main {

    public static BufferedImage getStrokedImage(
            BufferedImage bi, Shape shape, int strokeWidth) {
        int w = bi.getWidth();
        int h = bi.getHeight();
        BufferedImage bib = new BufferedImage(w,h,bi.getType());
        Graphics2D g = bib.createGraphics();

        BasicStroke bs = new BasicStroke(strokeWidth);
        g.setStroke(bs);
        Rectangle rect = new Rectangle(0,0,w,h); 
        TexturePaint tp = new TexturePaint(bi, rect); 
        g.setPaint(tp);
        g.draw(shape);

        g.dispose();
        return bib;
    }

    public static void main(String[] args) throws Exception {
        URL url = new URL("http://www.java2s.com/style/download.png");
        final BufferedImage bi = ImageIO.read(url);
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                int strokeWidth = 12;
                int pad = 50;
                Shape shape = new Rectangle(
                        pad,pad,
                        bi.getWidth()-(2*pad),bi.getHeight()-(2*pad)); 
                Image i = getStrokedImage(bi, shape, strokeWidth);
                JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(i)));
            }
        });
    }
}