Issues with the method import_pixels from MiniMagick for Ruby

28 Views Asked by At

I am working with Ruby 3.1.0 and mini_magick 4.12.0. I would like to load the pixels of an image, change a few pixels (pixel by pixel), import the new pixel data to a new image object and write the new image to the disk.

Here is the code:

require 'mini_magick'

img1 = MiniMagick::Image.open("img1.jpg")
pixels = img1.get_pixels
puts "pixels[0][0][0] = #{pixels[0][0][0]}"
pixels[0][0][0] = 12
blob = pixels.flatten.pack('C*')
img2 = MiniMagick::Image.import_pixels(blob, img1.width, img1.height, 8, "rgb", "jpg")
img2.write("img2.jpg")
pixels2 = img2.get_pixels
puts "pixels2[0][0][0] = #{pixels2[0][0][0]}"

When I run the above code, I get the following response:

pixels[0][0][0] = 46
pixels2[0][0][0] = 33

When I was expecting:

pixels[0][0][0] = 46
pixels2[0][0][0] = 12

Running the identify method on both objects gives me the following:

img1.identify: /var/folders/89/vk0gfkbs2vg89110hxpbxtcc0000gn/T/mini_magick20230626-45043-n4imik.jpg JPEG 400x250 400x250+0+0 8-bit sRGB 27506B 0.000u 0:00.000
img2.identify: /var/folders/89/vk0gfkbs2vg89110hxpbxtcc0000gn/T/mini_magick20230626-45043-7m053n.jpg JPEG 400x250 400x250+0+0 8-bit sRGB 37072B 0.000u 0:00.000

When I open the new image, I get the same pixel value for the first pixel of the first channel:

img3 = MiniMagick::Image.open("img2.jpg")
pixels3 = img3.get_pixels
puts "pixels3[0][0][0] = #{pixels3[0][0][0]}"

Which returns:

33

What am I missing?

0

There are 0 best solutions below