How to iterate through pixels of an image?

I would like to create a script that involves scanning through the pixels of an image so I can create an export ready variation of it. Basically, I’d like to scan from left to right, top to bottom across the image, sample the sprite as a whole at this coordinate (ie, the pixel value of what the flattened image would be), and then use this value as input for another function which is constructing a new image in a new sprite. I’m having a lot of trouble trying to sample a value and no matter what I try I am just getting 0 values back from getPixel(). How to I sample my image at a given coordinate?

you need to use two nested loops. like this:

function fMain() 
	-- scan through all pixels in selected cel 
	for yy = 0, img_h-1, 1 do 
		for xx = 0, img_w-1, 1 do 
			-- get pixel value 
			clr_i = img.image:getPixel(xx,yy); 
		end 
	end 

this is taken from another script, so you have to provide variables: img (active cel), its width (img_w) and height (img_h).

I would also recomment using Image:pixels(), it’s a handy iterator that let’s you do the same thing but with one loop.

1 Like

Is there any way to sample the color from the entire image rather than just a single cell? My sprite may have multiple layers.

Not sure if there’s a simpler way but I always achieved this by making a temporary image in the size of the sprite, drawing the sprite using Image:drawSprite() on the temporary image and sampling from there.

This gives you a flat image with all the layers merged without modifying the sprite.

1 Like