Skip to main content

Obtain Shape/Area Object for BufferedImage (Irregular Shape) Outline bounds

1 reply [Last post]
sharath_tc
Offline
Joined: 2008-08-13
Points: 0

Is it possible to obtain almost precise boundaries and hence Shape or Area object on irregular buffered image (a PNG image with transparency) and HOW?

thanks and regards

sharath

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
pietblok
Offline
Joined: 2003-07-17
Points: 0

Hi,

Just out of curiosity and extremely slow. High CPU load.

Piet

[code]
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;

import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class ImageBoundaries {

public static Area getArea(BufferedImage image, int maxTransparency) {
Area area = new Area();
Rectangle rectangle = new Rectangle();
for (int x = 0; x < image.getWidth(); x++) {
for (int y = 0; y < image.getHeight(); y++) {
int rgb = image.getRGB(x, y);
rgb = rgb >>> 24;
if (rgb >= maxTransparency) {
rectangle.setBounds(x, y, 1, 1);
area.add(new Area(rectangle));
}
}
}
return area;
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
BufferedImage image = new BufferedImage(200, 200,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();

g.setColor(new Color(0, 0, 0, 0));
g.fillRect(0, 0, 200, 200);

g.setColor(new Color(0, 0, 0, 16));
Ellipse2D ellipse = new Ellipse2D.Double(0, 0, 200, 200);
g.fill(ellipse);

g.setColor(new Color(0, 0, 0, 32));
ellipse = new Ellipse2D.Double(50, 50, 100, 100);
g.fill(ellipse);

g.dispose();
final Area bounds = ImageBoundaries.getArea(image, 25);
final Icon icon = new Icon() {

@Override
public int getIconHeight() {
return 200;
}

@Override
public int getIconWidth() {
return 200;
}

@Override
public void paintIcon(Component component, Graphics g,
int x, int y) {
((Graphics2D) g).fill(bounds);
((Graphics2D) g).drawRect(0, 0, 199, 199);
}
};
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JLabel(icon));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});

}

}
[/code]