Crop to main non-alpha portion of a PImage?

edited October 2013 in How To...

I'm hoping someone can help me with this. I want to create a function that takes a PImage, say 640x640 in size, and crops it to the non-alpha area bounds of the image. It would then return that image.

As an example, the 640x640 PImage it takes is fully transparent except for a circle of 50 pixels in diameter. The function would crop to that circle and return a PImage of 50x50 with the circle. It would also be useful to indicate a buffer area around the subject, i.e. the circle, and pad it with transparent pixels. Say you wanted a padding of 10 pixels per side, the fuction would return a PImage of 70x70 with the circle. Did I make that clear enough?

Thanks.

Answers

  • This can be easily done by:

    • Start with two Points: Point min(x=image Width, Y=Image Height) and Point max(x=0, y=0).
    • with two for cycles, go through every pixel of the image.
    • If a pixel is opaque, then check if it's x position is greater than the current x max position. If it is, store it. Also check if the x position is lesser than the current x min position. If it is, store it.
    • If a pixel is opaque, then check if it's y position is greater than the current y max position. If it is, store it. Also check if the y position is lesser than the current y min position. If it is, store it.

    You will end with two points that will define the square region you have to crop.

  • Thanks, I'll put something together with your suggestions. That makes sense.

  • Answer ✓

    Perhaps simpler, and faster: examine each row of pixels, starting from top (downward) and from bottom (upward). Just stop each search when you meet an opaque pixel, you found out minY and maxY.

    Do the same for columns of pixels: from left (to the right) and from right (to the left). Gives minX and maxX.

    Crop the image at these positions.

    No need to explore the whole image.

Sign In or Register to comment.