实现此图像效果的最佳方法是什么?使用PHP GD或JS Canvas?

时间:2012-01-21 20:05:33

标签: php javascript image-processing canvas gd

我正在尝试重新创造这种效果(王冠):

enter image description here

用户上传图像并将暗像素变为黑色并且亮像素清晰。这会是一个好方法吗?

我也在SO:How do you convert an image to black and white in PHP

上发现了这一点

但我不确定如何实施它。

人们会推荐使用JS Canvas还是PHP的GD?

我不会一次又一次地创建图像,我会处理它并将其移动到目录以供将来使用

2 个答案:

答案 0 :(得分:2)

以下是如何在JS中执行此操作。请注意,图像必须来自同一个域才能正常工作:

var img = document.getElementById( 'imagebase' );
var canvas = document.getElementById( 'canvasEl' );

// Set Canvas widht and height
canvas.width = img.width;
canvas.height = img.height;

var ctx = canvas.getContext( '2d' );
ctx.drawImage( img, 0, 0, canvas.width, canvas.height );

// The loop
for ( var x = 0, l = canvas.width; x < l; x++ ) {
    for ( var y = 0, lh = canvas.height; y < lh; y++ ) {
        // Returns array [Red, Green, Blue, Alpha] each out of 255
        var data = ctx.getImageData(x,y,1,1);
        // Thresholding: More black than white, and more transparent than not
        if ( ( data[0]+data[1]+data[2] ) / 3 < ( 255 / 2 ) && data[3] > 255 / 2 ) {
            // Set to black with full opacity
            data[0] = 0, data[1] = 0, data[2] = 0, data[3] = 255;
        } else {
            // Set to transparent
            data[3] = 0;
        }
        ctx.putImageData( data, x, y );
    }
}

我用虚拟ID来向你展示工作原理。另外,请查看this page以获取有关像素操作的更多信息。

也就是说,这需要画布才能工作,因此旧IE中不支持它(除非你使用Google的替换画布,但我不确定它是否支持所有这些方法)。优点是它为每个用户而不是服务器上的所有用户带来了负担。

答案 1 :(得分:1)

我建议您使用raphaeljs进行绘图,对于像皇冠这样的对象,您可以绘制它们,也可以使用图像。使用它制作2位图像也会更容易!