Search code examples
rubyimagemagickminimagick

Manipulate pixels using Minimagick


Is there a way to manipulate pixels and create or modify the manipulated image to reflect the changes made to the pixels ?

Minimagick only provides a get_pixels method.

Should I convert the array to a string and use the import_pixels method ? but then, how can I reconvert the pixels to a blob ?


Solution

  • Correct, you should use the import_pixels method. Here's a full example:

    # get pixels
    img = MiniMagick::Image.open("image.jpg")
    pixels = img.get_pixels
    
    # transform pixels
    reverse = pixels.map(&:reverse)
    
    # save pixels
    blob = reverse.flatten.pack("C*")
    img = MiniMagick::Image.import_pixels(blob, img.width, img.height, 8, "rgb", "jpg")
    img.write("reverse.jpg")