简体   繁体   English

Javascript Canvas获取图像像素数据

[英]Javascript Canvas Get images pixel data

I have a two part question about javascript canvas: 我有两个关于javascript canvas的问题:

Part 1: 第1部分:
I have a .jpg in the same file as my html document. 我在与html文档相同的文件中有一个.jpg。 I was wondering if there was a simple way of getting a pixel's color in that file without having to use context.getImageData(). 我想知道是否有一种简单的方法可以在该文件中获取像素的颜色,而无需使用context.getImageData()。

Part 2: (If part 1 is too complex to be useful.) 第2部分:(如果第1部分过于复杂而无法使用。)
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: 如果我直接从这个站点复制代码: W3学校将getImageData()放到桌面上的html文件中,并将一个名为img_the_scream.jpg的图像添加到我的桌面,然后运行它我收到此错误:

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 . 这是同源策略所施加的限制:如果服务器明确允许使用CORS头,则无法读取由另一个源提供的JavaScript数据。

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. 如果你想获得由另一台服务器服务的图像像素,而这个服务器没有设置这个标头,那么你必须使用一种代理或者通过获取图像服务器来处理你的服务器。侧。

Note that browsers consider all files coming from file:// to be of different origin. 请注意,浏览器会将来自file://所有文件视为来源不同。 If you try to do it locally, you must use an http server. 如果您尝试在本地执行此操作,则必须使用http服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM