Search code examples
javaimageimage-processingjava-2dstroke

Apply stroke to an image in Java


I would like to apply a stroke (outline) to an image in Java. After reading this and this it looks like Java2D API applies strokes to shapes only? Surely I can do a bitmap fill and then apply a stroke to that shape but I want to know if I can apply it directly on the given bitmap.

UPDATE: I managed to apply a stroke bit it outlines the whole image.My images have PNG transparency.How do I apply the stroke around the visible pixels of the image only ?

 public static void main(String[] args) {
    try {
        // TODO code application logic here
        URL u = GraphicsDemo.class.getResource("Capture222.png");
        BufferedImage img = ImageIO.read(new File(u.getPath()));
        System.out.print("loaded");
        Graphics2D g = img.createGraphics();
        Rectangle2D tr = new Rectangle2D.Double(0, 0,
                img.getWidth(), img.getHeight());
        // Create the TexturePaint.
        TexturePaint tp = new TexturePaint(img, tr);
        g.setStroke(new BasicStroke(20));
        g.setPaint(Color.ORANGE);
        //   g.fill(tr);
        g.draw(tr);


        ImageIO.write(img, "PNG", new File("myeditedimage.png"));
        g.dispose();
    } catch (IOException ex) {
        Logger.getLogger(GraphicsDemo.class.getName()).log(Level.SEVERE, null, ex);
    }
 } 

UPDATE 1: I am not sure what I am trying to do is possible using Java Graphics API.Once again.I need to outline the image based on the visible pixels contour and not around it's bounding box. That is what I am trying to achieve: enter image description here


Solution

  • Yes, the Java2D API applies strokes to shapes only. You can do two things:

    Either create a Shape out of the transparency information of your bitmap image, so that you can stroke only the non-transparent part. This is difficult in any language, because it means converting the bitmap-information into a vector-based information.

    Check this: Image/Graphic into a Shape

    And this: Smoothing a jagged path

    But basically I would try to avoid the converting problem, and solve it in a bitmap-only way - for example, colorize those pixels (with the "stroke color") for which a transparent pixel can be found at a given pixel-distance ("stroke width").