Posted By

oozolii on 08/12/11


Tagged


Versions (?)

gray scale img


 / Published in: JavaScript
 

  1. <html>
  2. <head>
  3.  
  4. </head>
  5. <body>
  6. <ul class="talalat">
  7. <li>
  8. <img src="image3.jpg" class="img_grayscale" onload="grayscale(this)">
  9. </li>
  10. </ul>
  11. <script>
  12.  
  13. /*var imgs = document.querySelectorAll('.talalat li');
  14. for(var i=0;i<imgs.length;i++) {
  15. console.log(imgs[i].querySelector('img').src);
  16. imgs[i].querySelector('img').src = grayscale(imgs[i].querySelector('img').src);
  17. }*/
  18.  
  19. function grayscale(el){
  20. src = el.src;
  21. var canvas = document.createElement('canvas');
  22. var ctx = canvas.getContext('2d');
  23. var imgObj = new Image();
  24. imgObj.src = src;
  25. console.log(src);
  26. canvas.width = imgObj.width;
  27. canvas.height = imgObj.height;
  28. ctx.drawImage(imgObj, 0, 0);
  29. var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
  30. for(var y = 0; y < imgPixels.height; y++){
  31. for(var x = 0; x < imgPixels.width; x++){
  32. var i = (y * 4) * imgPixels.width + x * 4;
  33. var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
  34. imgPixels.data[i] = avg;
  35. imgPixels.data[i + 1] = avg;
  36. imgPixels.data[i + 2] = avg;
  37. }
  38. }
  39. ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
  40. el.src=canvas.toDataURL();
  41. }
  42.  
  43. </script>
  44. </body>
  45. </html>

Report this snippet  

You need to login to post a comment.