How to get a pixel's x,y coordinate color from an image?

后端 未结 4 1919
时光说笑
时光说笑 2020-11-22 09:00

Is there any way to check if a selected(x,y) point of a PNG image is transparent?

4条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 09:57

    The two previous answers demonstrate how to use Canvas and ImageData. I would like to propose an answer with runnable example and using an image processing framework, so you don't need to handle the pixel data manually.

    MarvinJ provides the method image.getAlphaComponent(x,y) which simply returns the transparency value for the pixel in x,y coordinate. If this value is 0, pixel is totally transparent, values between 1 and 254 are transparency levels, finally 255 is opaque.

    For demonstrating I've used the image below (300x300) with transparent background and two pixels at coordinates (0,0) and (150,150).

    Console output:

    (0,0): TRANSPARENT
    (150,150): NOT_TRANSPARENT

    image = new MarvinImage();
    image.load("https://i.imgur.com/eLZVbQG.png", imageLoaded);
    
    function imageLoaded(){
      console.log("(0,0): "+(image.getAlphaComponent(0,0) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));
      console.log("(150,150): "+(image.getAlphaComponent(150,150) > 0 ? "NOT_TRANSPARENT" : "TRANSPARENT"));
    }

提交回复
热议问题