How do you convert a color image to black/white using Javascript?

后端 未结 9 1374
梦如初夏
梦如初夏 2020-12-05 11:01

How do you convert a color image to black/white using only Javascript?

AND, also make it cross compatible in most browsers because I hear Internet E

相关标签:
9条回答
  • 2020-12-05 11:37

    The way I would do it is to set the src of the img to point to a server-side PHP script

    eg.,

    <img src="http://mysite/grayscale.php?url='...'
    

    That script fetches the image, runs some GD code, and returns a JPG. Something like this

    0 讨论(0)
  • 2020-12-05 11:39

    Despite my initial scepticism it appears that such magic is indeed possible, using the new Canvas functionality in some browsers.

    This page shows how to do it using browsers that support Canvas:

    http://www.permadi.com/tutorial/jsCanvasGrayscale/index.html

    For IE you need to use filters, there is an example of doing greyscale here:

    http://www.javascriptkit.com/filters/basicimage.shtml

    0 讨论(0)
  • 2020-12-05 11:41

    Modern browsers can now do this in CSS – on any HTML element, not just images. Combined with IE's old filter CSS, you can get pretty good compatibility:

    image.grayscale {
      /* IE */
      filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
    
      /* Chrome, Safari */
      -webkit-filter: grayscale(1);
    
      /* Firefox */
      filter: grayscale(1);
    }
    

    OP specifies "only JavaScript" but also mentions that IE's filter would be acceptable if it were more widely supported, which it now (effectively) is, so I believe this is the best solution in 2015. If you really must have JavaScript:

    element.style.filter = 'grayscale(1)';
    

    Sources:

    • Browser support
    • Spec
    • Tutorial
    0 讨论(0)
提交回复
热议问题