简体   繁体   English

使用html canvas和JS处理图像上的像素数据

[英]Manipulating pixel data on image with html canvas and JS

OK, so I'm trying to take an image on my machine and manipulate it using a canvas and some JS... However, I keep getting the error: OK,所以我试图在计算机上拍摄图像并使用画布和一些JS操作它。但是,我不断收到错误消息:

"Image from origin 'file://' has been blocked from loading by Cross-Origin Resource Sharing policy: Invalid response. Origin 'null' is therefore not allowed access. " “跨源资源共享策略已阻止从原始文件'file://'加载图像:无效的响应。因此,不允许访问原始'null'。”

I thought that if I didn't modify the original image, and only modified a copy of the image data, I would be ok. 我以为,如果我不修改原始图像,而只修改图像数据的副本,那会没事的。 But for some reason, it still doesn't work. 但是由于某种原因,它仍然无法正常工作。 Anyone know what I should do? 有人知道我应该怎么做吗? This is the code I have currently: 这是我目前拥有的代码:

$(document).ready(function() {
  var canv = document.getElementById("img_canvas");
  var ctx = canv.getContext("2d");
  var img = new Image();
  img.crossOrigin = "Anonymous";
  img.src = "img/meAndTheOcean.jpg";

  $(img).load(function() {
    ctx.drawImage(img, 0, 0);
    var img_data = ctx.getImageData(0,0,canv.width, canv.height);
    var pixels = img_data.data;
    var npixels = img_data.width * img_data.height;
    var cpyPixels = ctx.createImageData(img_data.width, img_data.height);
    for (var i = 0; i < npixels; i++){
      cpyPixels[i*4] = 255 - pixels[i*4];
      cpyPixels[i*4 + 1] = 255 - pixels[i*4 + 1];
      cpyPixels[i*4 + 2] = 255 - pixels[i*4 + 2];
    }
    ctx.putImageData(cpyPixels,0,0);
  });
});

You are very likely have this page opened simply by double clicking the html file. 您很可能只需双击html文件即可打开此页面。 and not on a local server, which you can easily start and get such as nodejs or wamp. 而不是在本地服务器上,您可以轻松启动并获取它,例如nodejs或wamp。

You can not load images from file source it results in origin of image being different from origin of domain. 您无法从文件源加载图像,这会导致图像的来源与域的来源不同。

This is called Tainted canvas, more on this here: https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image 这被称为污染的画布,更多信息在这里: https : //developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image

It means that for security reason you are not allowed to access canvas data. 这意味着出于安全原因,不允许您访问画布数据。 http://simonsarris.com/blog/480-understanding-the-html5-canvas-image-security-rules http://simonsarris.com/blog/480-understanding-the-html5-canvas-image-security-rules

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

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