简体   繁体   English

Javascript获取Facebook个人资料图像像素数据

[英]Javascript Get Facebook Profile Image Pixel Data

I need to get the pixel data from a random user's Facebook profile image so I can pass it through Emscripten to our C++ app. 我需要从随机用户的Facebook个人资料图像中获取像素数据,以便将其通过Emscripten传递给我们的C ++应用。 That is, I need the RGB values of each pixel. 也就是说,我需要每个像素的RGB值。 I've tried lots of different ways, using the Javascript FBSDK, graph calls, downloading images, and trying to draw to a canvas I've created but I run into all sorts of issues, eg cross domain problems. 我尝试了许多不同的方法,使用Javascript FBSDK,图形调用,下载图像,并尝试绘制到我创建的画布上,但是遇到了各种各样的问题,例如跨域问题。 I don't need it to be rendered to a visible canvas, I just need toe data to pass back to our app. 我不需要将其渲染到可见的画布上,只需要将脚趾数据传递回我们的应用即可。

Is there a simple way please ? 请问有简单的方法吗?

You can get the image pixel data from Facebook, fetching the image via an Ajax request rather than an img tag. 您可以从Facebook获取图像像素数据,并通过Ajax请求而非img标签获取图像。

Specifically, you can: 具体来说,您可以:

  • Fetch the image data using an XMLHttpRequest 使用XMLHttpRequest获取图像数据
  • Wrap up the data in a Blob 将数据包装在Blob
  • Set the src of an Image to an object URL of the blob Imagesrc设置为Blob的对象URL
  • On load of the image, put the image on a canvas, using the canvas context's drawImage 加载图像后,使用画布上下文的drawImage将图像放在画布上
  • Get the pixel data using the context's getImageData 使用上下文的getImageData获取像素数据

The below. 下面。 code works for me, on Chrome, without any security issues 代码在Chrome上对我有效,没有任何安全问题

document.addEventListener('DOMContentLoaded', function() {
  var xhr = new XMLHttpRequest();
  xhr.responseType = 'arraybuffer';
  xhr.addEventListener("load", onResponse);
  xhr.open("GET", "http://graph.facebook.com/61308470/picture");
  xhr.send();

  var image = new Image();
  var canvas = document.getElementById('canvas');
  var context = canvas.getContext('2d');

  function onResponse() {
    var blob = new Blob([xhr.response], {type: 'image/jpeg'});
    var url = (window.URL || window.webkitURL).createObjectURL(blob);
    image.src = url;
  }

  image.onload = function() {
    context.drawImage(image, 0, 0);
    var data = context.getImageData(0, 0, 50, 50).data;

    // Pixel data of the image
    console.log(data);

    // Cleanup
    (window.URL || window.webkitURL).revokeObjectURL(url);
  }
});

You can see this at http://plnkr.co/edit/fEwoIQRQhaCDRHkwNdvr?p=preview 您可以在http://plnkr.co/edit/fEwoIQRQhaCDRHkwNdvr?p=preview中看到此内容

For reference, it looks like the Facebook profile pictures do set the headers for cross domain ajax. 作为参考,Facebook个人资料图片确实为跨域ajax设置了标头。 Specifically, the responses set access-control-allow-origin: * . 具体而言,响应设置access-control-allow-origin: *

I based this on this answer to "Using raw image data from ajax request for data URI" 我基于“使用来自Ajax请求数据URI的原始图像数据”的答案

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

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