15

あたかも html5 キャンバス要素であるかのように、html 画像に含まれるデータを動的に変更/アクセスする方法があるかどうかを知りたいです。キャンバスを使用すると、javascript で getImageData() と putImageData() を使用して生のピクセル データにアクセスできますが、これまでのところ、画像でこれを行う方法を理解できていません。

4

7 に答える 7

21
    // 1) Create a canvas, either on the page or simply in code
    var canvas = document.createElement('canvas');
    var ctx    = canvas.getContext('2d');

    // 2) Copy your image data into the canvas
    var myImgElement = document.getElementById('foo');
    ctx.drawImage( myImgElement, 0, 0 );

    // 3) Read your image data
    var w = myImgElement.width, h=myImgElement.height;
    var imgdata = ctx.getImageData(0,0,w,h);
    var rgba = imgdata.data;
    
    // 4) Read or manipulate the rgba as you wish
    for (var px=0,ct=w*h*4;px<ct;px+=4){
      var r = rgba[px  ];
      var g = rgba[px+1];
      var b = rgba[px+2];
      var a = rgba[px+3];
    }

    // 5) Update the context with newly-modified data
    ctx.putImageData(imgdata,0,0);

    // 6) Draw the image data elsewhere, if you wish
    someOtherContext.drawImage( ctx.canvas, 0, 0 );

ステップ 2 は、ページ上ではなく、スクリプトに直接読み込まれた画像からも取り込むことができることに注意してください。

    // 2b) Load an image from which to get data
    var img = new Image;
    img.onload = function(){
      ctx.drawImage( img, 0, 0 );
      // ...and then steps 3 and on
    };
    img.src = "/images/foo.png"; // set this *after* onload
于 2010-11-30T00:20:25.123 に答える
6

drawImage()を使用してキャンバス要素に画像を描画し、キャンバスからピクセル データを取得できます。

于 2009-09-18T17:34:43.780 に答える
4

このコードでいくつかの問題が発生した後、Phrogz の回答に 1 つまたは 2 つのことを追加したいと思います。

// 1) Create a canvas, either on the page or simply in code
var myImgElement = document.getElementById('foo');
var w = myImgElement.width, h=myImgElement.height; // New : you need to set the canvas size if you don't want bug with images that makes more than 300*150

var canvas = document.createElement('canvas');
canvas.height = h;
canvas.width = w;
var ctx    = canvas.getContext('2d');

// 2) Copy your image data into the canvas
ctx.drawImage( myImgElement, 0, 0, w, h ); // Just in case...

// 3) Read your image data
var imgdata = ctx.getImageData(0,0,w,h);
var rgba = imgdata.data;

// And then continue as in the other code !
于 2013-01-17T19:30:14.483 に答える
1

you first want to draw a pic on the canvas and then get the imageData from the canvas ,it is a wrong way,because the js think it is a "Cross-domain access",but the getIamgeData method don't allow the "Cross-domain access" to an image.you can hava a try by put the in the root place and access it by "localhost" .

于 2012-04-16T02:26:06.777 に答える
0

可能かどうかはわかりませんが、PHP からピクセル情報を要求してみることができます。GD ライブラリであれば簡単な作業ですが、確実に遅くなります。アプリケーションを指定しなかったので、画像をクエリまたは変更できるよりもベクター画像である可能性がある場合は、このタスクで SVG を確認することをお勧めします。

于 2009-09-18T17:32:29.720 に答える