Javascript Canvas获取图像像素数据 [英] Javascript Canvas Get images pixel data
问题描述
我有一个关于javascript canvas的两部分问题:
I have a two part question about javascript canvas:
第1部分:
我有一个.jpg在与我的HTML文档相同的文件。我想知道是否有一个简单的方法来获取像素的颜色在该文件,而无需使用context.getImageData()。
Part 1:
I have a .jpg in the same file as my html document. I was wondering if there was a simple way of getting a pixel's color in that file without having to use context.getImageData().
第2部分: (如果第1部分过于复杂,无法使用)
如果我直接从此网站复制代码: W3学校的getImageData()添加到我的桌面上的html文件,并在我的桌面上添加一个名为 img_the_scream.jpg 的图片,然后运行它我收到此错误:
Part 2: (If part 1 is too complex to be useful.)
If I directly copy the code from this site: W3 schools getImageData() into an html file on my desktop, and add an image named img_the_scream.jpg to my desktop, then run it I get this error:
Unable to get image data from canvas because the canvas has been tainted by cross-origin data. test.html:15
Uncaught Error: SecurityError: DOM Exception 18
真的知道为什么它为网站工作,但不是为我。
I don't really know why it works for the site but not for me.
推荐答案
That's a limit imposed by the Same Origin Policy : you can't read in JavaScript data served by another origin apart if the server explicitly allows it using CORS headers.
如果你想获得一个图像的像素由服务器之外的另一个服务器,而不是你的服务器并没有设置这个头,那么你必须在你的服务器上工作,通过使用一种代理或通过获取图像服务器
If you want to get the pixels of an image served by another server than yours and this server doesn't set this header, then you'll have to work on your server, either by using a kind of proxy or by fetching the image server side.
请注意,浏览器会将来自 file://
的所有文件视为不同的来源。如果您尝试在本地执行此操作,则必须使用http服务器。
Note that browsers consider all files coming from file://
to be of different origin. If you try to do it locally, you must use an http server.
这篇关于Javascript Canvas获取图像像素数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!