How do I crop an image using a color pattern?

I am developing a small program that slices images by color.

It's easiest to explain with this example image:

black with a purple splotch of color

And I want to create a new image with only purple shape, no black border.

Does anyone have any ideas? I'm using Java 2D, so I believe I need to create a Shape object with a purple area of ​​the first image.

+2


a source to share


2 answers


If the image literally looks like the image you are showing, you can:

  • load the image into BufferedImage (with ImageIO.read ())
  • create a new BufferedImage of the same size, ensuring that it is at alpha level (for example, set its type to BufferedImage.TYPE_4BYTE_ABGR)
  • "manually" traverses each pixel in turn in the loaded BufferedImage, getting the pixel's color using getRGB () and checking if it's black
  • if the color is black, set the corresponding pixel to transparent in the new image, otherwise the original color from the first image (see the setRGB () method)
  • save new image (using ImageIO.write ())


There are more fun ways, but this simple method is nice and straightforward and will work great for the type of images you showed.

+5


a source


You need to use some kind of fill algorithm that will find the borders of the purple area:

Wikipedia has a page with excellent pseudocode and animation.



http://en.wikipedia.org/wiki/Flood_fill

+2


a source







All Articles