开发者

How can i calculate where the non transparent part of an image starts and ends with PHP?

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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜