我怎样才能用PHP计算图像的非透明部分的开始和结束位置?

发布于 2024-09-08 19:35:33 字数 186 浏览 5 评论 0原文

这里有一个问题:假设我们有一个 200x200 的透明 png 图像,并且有一个从 x,y (50,50) 开始、宽度为 50px、高度为 20px 的形状。

有没有办法使用 PHP(gdlib 或 imagemagick)来获取形状相对于图像大小的位置?对于给定的示例,脚本应返回 (x1=50, y1=70, x2=100, y2=70)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

琉璃繁缕 2024-09-15 19:35:33

“形状始于”是什么意思?例如,对于椭圆形,您想找到覆盖整个椭圆形的矩形的左上角?

如果是,那么您可以从上到下循环遍历图像的每个像素(getpixel 将为您提供像素的颜色),搜索不透明的最顶部和最底部点(结束循环)当发现时)。这将是您的 y1y2 点。然后,您在 y1 - y2 范围内从左到右循环执行相同的操作,以找到 x1x2

这可能不是很优化,因此您可能需要想象一个更好的算法。例如,如果图像为 300×200 像素,则可以通过以下方式搜索最上面的点:

  1. 查看第 100 行(高度 / 2)是否有对象。
  2. 如果是这样,则查找第 50 行 (100 / 2)。
  3. 如果第 50 行包含对象,则扫描第 25 行 (50 / 2)。
  4. 让我们假设第 25 行是透明的。您可能需要查看第 38 行 (25 / 2 + 25)。
  5. 如果第 38 行不透明,您可以查看第 32 行 ([25 / 2] / 2 + 25)。
  6. ...

顺便说一下,假设当您扫描第 25 行时,您在坐标 x = 74, y = 50 处发现了一个非透明点。现在,当以相同的方式搜索最左边的点时,您可以从 37 (74 / 2) 开始,而不是从 x = 150 (width / 2) 开始,因为您已经知道有 < strong>是一个位于x = 74的对象。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文