如何使用 javascript 从图像中获取平均颜色或主颜色?
我想要的是从图像到另一个 div 背景的这种颜色的十六进制或 RGB 平均值。
因此,如果我上传带有大量红色的图像,我会得到类似 #FF0000 的内容作为示例。
让我知道这是否可行:)
非常感谢。
what i want is to the the HEX or the RGB average value from an image to the another div background this color.
So if i upload an image with a ot of red i get something like #FF0000 just as an example.
Let Me know if this is posible :)
Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
首先,在画布上绘制图像:
您现在可以迭代图像的像素。颜色检测的一种简单方法是简单地计算图像中每种颜色的频率。
getColors
返回颜色名称和计数的映射。透明像素被跳过。从这张地图中获取最常见的颜色应该是微不足道的。如果您确实想要每个颜色分量的平均值,您也可以从
getColors
的结果中轻松获得,但结果可能不太有用。 这个答案解释了一种更好的方法。您可以像这样使用它:
请参阅工作示例。
First, draw the image on a
canvas
:You can now iterate over the image's pixels. A naive approach for color-detection is to simply count the frequency of each color in the image.
getColors
returns a map of color names and counts. Transparent pixels are skipped. It should be trivial to get the most-frequently seen color from this map.If you literally want an average of each color component, you could easily get that from the results of
getColors
, too, but the results aren't likely to be very useful. This answer explains a much better approach.You can use it all like this:
See a working example.
这只能使用此处描述的画布标签:
http://dev.opera.com/articles/view/html-5-canvas-the-basics/#pixelbasedmanipulation
当然,这仅在较新的浏览器中可用
This is only possible using the canvas tag as described here :
http://dev.opera.com/articles/view/html-5-canvas-the-basics/#pixelbasedmanipulation
Of course this is only available in newer browsers
您可能会考虑使用 css 允许您应用的卷积过滤器。这也许能够获得您想要的效果(假设您想将其呈现回 html 中)。所以你可以显示图像两次,一次是卷积的。
话虽如此,如果您出于某种目的自己需要这些信息,那么这并不起作用。
You might consider using the convolution filters css allows you to apply. This might be able to get the effect you're going for ( assuming you're wanting to present it back into the html). So you could display the image twice , one convolved.
That being said, doesn't really work if you need the information yourself for some purpose.
2023 年更新:有一个 javascript 库可以做到这一点:
颜色小偷 - https://lokeshdhakar.com/projects/color-thief /
Update 2023: There is a javascript lib to do just that:
Color Thief - https://lokeshdhakar.com/projects/color-thief/
要找到平均颜色:
For finding that average color: