How To Turn Colors Into Shades Of Grey

play with images using canvas

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 Colors Into Shades Of Grey?

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 />
   Sorry
</canvas>
<script>
   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);      
   }    
</script> 


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): 


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



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

<script>
drawImageInGrey(ctx, mycanvas);
</script>


Share on Google Plus

About Mr.Ikram

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment