Get pixels and colours from NSImage

后端 未结 6 1285
南方客
南方客 2021-02-06 03:10

I have created an NSImage object, and ideally would like to determine how many of each pixels colour it contains. Is this possible?

6条回答
  •  清歌不尽
    2021-02-06 03:48

    This maybe a more streamlined approach for some and reduce complexity of dropping into memory management.

    https://github.com/koher/EasyImagy

    Code sample https://github.com/koher/EasyImagyCameraSample

    import EasyImagy
    
    let image = Image>(nsImage: "test.png") // N.B. init with nsImage 
    
    print(image[x, y])
    image[x, y] = RGBA(red: 255, green: 0, blue: 0, alpha: 127)
    image[x, y] = RGBA(0xFF00007F) // red: 255, green: 0, blue: 0, alpha: 127
    
    // Iterates over all pixels
    for pixel in image {
        // ...
    }
    
    
    
    //// Gets a pixel by subscripts Gets a pixel by  
    let pixel = image[x, y]
    // Sets a pixel by subscripts
    image[x, y] = RGBA(0xFF0000FF)
    image[x, y].alpha = 127
    // Safe get for a pixel
    if let pixel = image.pixelAt(x: x, y: y) {
        print(pixel.red)
        print(pixel.green)
        print(pixel.blue)
        print(pixel.alpha)
    
        print(pixel.gray) // (red + green + blue) / 3
        print(pixel) // formatted like "#FF0000FF"
    } else {
        // `pixel` is safe: `nil` is returned when out of bounds
        print("Out of bounds")
    }
    

提交回复
热议问题