I'm relativly new to Ruby, or Programming at all, so please excuse me, if i'm making a "noob2 mistake with the logic here.
I am trying to get an output of rgba pixel values in binary for every pixel in an image (and it's location), using Chunky_PNG.
While the output is correct it only displays the first row, seems so as if the outer loop would only run once.
Is there a logical fault in it, or does a while loop in a while loop never work ? That it may be bad practice to do so, i can imagine, but i would still like to know why it doesn't what it's supposed.
require 'chunky_png'
image = ChunkyPNG::Image.from_file('test.png')
#vars
$width0 = 0
$widthmax = image.dimension.width.to_i
$height0 = 0
$heightmax = image.dimension.height.to_i
#main
while $height0 < $heightmax do
while $width0 < $widthmax do
puts image[$width0,$height0].to_s(2)[0..7] + " " + image[0,0].to_s(2)[8..15] + " " + image[0,0].to_s(2)[16..23] + " " + $height0.to_s + "," + $width0.to_s
$width0 += 1
end
width0 = 0
$height0 += 1
end
You are missing a
$
You have
But you want
This has the effect of never resetting $width0 back to zero, so only the first row is output. It thinks the inner loop never has to run again, since
$width0
is still at its maximum value in every iteration after the first one.(I should probably also add that globals are not the best idea, as others have pointed out, but you did ask for the reason why the script only output the first row. :) )