views:

85

answers:

1

Hi people,

Here's a question: let's say we have a png image 200x200 that is transparent and there is a shape that starts at x,y (50,50) and has a width of 50px and height 20px.

Is there any way with PHP (gdlib or imagemagick) that i could get the position of the shape relative to the image size? For the example given the script should return (x1=50, y1=70, x2=100, y2=70)

+3  A: 

What does it mean "a shape that starts at"? For example for an ellipse, you want to find a top left corner of a rectangle which will cover the entire ellipse?

If yes, than you can loop through every pixel of an image (getpixel would give you the color of a pixel) from top to bottom searching for the topmost and bottommost point which is not transparent (ending the loop when found). It will be your y1 and y2 points. Then, you do the same thing looping from left to right inside y1 - y2 range to find x1 and x2.

This is probably not very optimized, so you may want to imagine a better algorithm. For example, if the image is 300×200 pixels, you may search for topmost point by:

  1. Seeing if there is an object at the row 100 (height / 2).
  2. If so, looking for a row 50 (100 / 2).
  3. If line 50 contains object, then you scan the line 25 (50 / 2).
  4. Let's imagine line 25 is transparent. You may need to look at line 38 (25 / 2 + 25).
  5. If line 38 is not transparent, you may look at the line 32 ([25 / 2] / 2 + 25).
  6. ...

By the way, let's say when you scanned line 25, you found a non-transparent point at the coordinates x = 74, y = 50. Now, when searching the same way for the leftmost point, instead of starting from x = 150 (width / 2), you can start from 37 (74 / 2), since you already know that there is an object at x = 74.

MainMa
Hi, thnx for the really useful answer. I'm interested in a rectangle for start. Doesn't this method (looping through every pixel) have too much overhead?
Fotis
Well, I imagine there are more optimized ways of doing things. Now, if you stop searching for topmost pixel once found, or for a rightmost pixel, etc., it already optimizes things quite a bit. I edited my question to include a suggestion of optimization (ie. to reduce overhead).
MainMa
Thank you very much
Fotis
Feel free to accept the answer. ;)
MainMa