Posted By

bionickid on 11/04/11


Tagged

image jquery grayscale


Versions (?)

grayscale


 / Published in: jQuery
 

  1. function grayscale(src){
  2. var canvas = document.createElement('canvas');
  3. var ctx = canvas.getContext('2d');
  4. var imgObj = new Image();
  5. imgObj.src = src;
  6. canvas.width = imgObj.width;
  7. canvas.height = imgObj.height;
  8. ctx.drawImage(imgObj, 0, 0);
  9. var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
  10. for(var y = 0; y < imgPixels.height; y++){
  11. for(var x = 0; x < imgPixels.width; x++){
  12. var i = (y * 4) * imgPixels.width + x * 4;
  13. var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
  14. imgPixels.data[i] = avg;
  15. imgPixels.data[i + 1] = avg;
  16. imgPixels.data[i + 2] = avg;
  17. }
  18. }
  19. ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
  20. return canvas.toDataURL();
  21. }
  22.  
  23. $(function() {
  24. $('img').attr('src',
  25. grayscale($('img').attr('src'))
  26. );
  27. });

Report this snippet  

You need to login to post a comment.