Search code examples
rubyimagemagickimagickmogrifyvips

Create a shape with libvips ruby


How can I convert a picture with any color and form to its shape? As an example I attached an input image and desired output. I need to make this conversion with ruby and ruby-vips gem. Generally speaking, I need to fill anything that is not alpha channel with single color.

Input

Output


Solution

  • You can use [ ] to get bands out of an image. Your image is RGBA, so 0, 1 and 2 are R, G and B, and 3 is A.

    alpha = image[3]
    

    alpha channel of sample image

    You can use ranges as well, so eg.:

    rgb = image[0..2]
    

    Gets the first three bands. bandsplit breaks an image into an array of one-band images:

    r, g, b, a = image.bandsplit
    

    The alpha has 0 for transparent and 255 for solid, and it sounds like you'd prefer the inverse of that. Therefore:

    mask = image[3].invert