1

I'm trying to recreate this effect (the crown):

enter image description here

Where the user uploads an image and it turns the dark pixels black and the light pixels clear. Would this be a good method?

I also spotted this on SO: How do you convert an image to black and white in PHP

But i'm not really sure how to implement it.

Would people recommend JS Canvas for this or PHP's GD?

I wouldnt be creating the images over and over each time, i would process it and move it to a directory for future use

Community
  • 1
  • 1
benhowdle89
  • 36,900
  • 69
  • 202
  • 331

2 Answers2

2

The following is how to do it in JS. Note that the image must be from the same domain to work properly:

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 );
    }
}

I've used dummy ID's to show you how things work. Also, check out this page for more information about pixel manipulation.

That said, this requires canvas to work so it won't be supported in older IE (unless you use Google's replacement canvas, but I'm not sure about its support for all of these methods). The advantage is that it puts the burden on each user instead of on your server for all users.

LoveAndCoding
  • 7,857
  • 2
  • 31
  • 55
1

I would suggest you to use raphaeljs for drawing, for objects like crown you can either draw them or you can use images. It also would be easier to make a 2bit image with this!

Waqar Alamgir
  • 9,828
  • 4
  • 30
  • 36