Saturday, 15 November 2014

How to turn Color Image into Black and White in Blogger's Post

Canvas is definitely a powerful tool and you can use it to turn color pictures into black and white pictures.

Actually turning colors into shades of grey is a simple manipulation: declare a canvas, load a picture and apply the transformation script.

How to turn Color Image  into Black and White in Blogger's Post

Here is a canvas loaded with the picture of a street in South-America:

Here is the HTML code that created the canvas and loaded the image (to be inserted in the HTML view of your post) :

<canvas height="400" id="myimage" width="500" style="margin-left:30px; ">
   Your browser does not support Canvas.
   <br />
   var mycanvas   = document.getElementById('myimage') ;
   if( mycanvas.getContext ) {
      var ctx = mycanvas.getContext('2d');
      var imageObj = new Image();
      imageObj.crossOrigin="anonymous" ;
      imageObj.src = 'https://dc788c82bdb50153.../street.jpg';
      ctx.drawImage(imageObj, 0, 0);     

A small customization is required to use this code:
1) the attributes of the canvas tag must be edited: replace the height and the width with the actual height and width in pixels of the image you want to display.
2) In this post, I used an image located on my google drive. Replace the source of the image ( imageObj.src ) with the actual URL of your image (it should be accessible from blogger).

Now that we know how to load a picture into an html canvas, let us see how we can transform this picture and turn colors into shades of grey. To do that we'll use a small javascript function that replaces colors with shades of grey. Insert the following script in your post (in the html view):

function drawImageInGrey(ctxObj, cvsObj  ) { 
var imgData=ctxObj.getImageData(0,0,cvsObj.width-1,cvsObj.height-1); 
var col = 0 ;
for (var i=0;i<;i+=4)
col = Math.floor( ([i] +[i+1] +[i+2] ) / 3 ) ;[i] = col;[i+1] = col;[i+2] = col;

Then apply the transformation to the canvas with the following javascript command (in the html view of your post):

drawImageInGrey(ctx, mycanvas);

Here is the result:

Actually using canvas and javascript, you can go further: turn colors into shades of a single color, replace a color with another, etc.

1 comment:

  1. Really interesting blog post, but its all about engineering nothing else, great blog post from JEE Main 2015 Result Date