Hey guys!
In my latest project I need to copy the colors of pixels of an image into rectangles in a mesh, but using image:get() seems to return the wrong value. I noticed that the new value changes depending on the alpha value, so I tried multiplying the red, green, and blue values by 255/alpha and it looks like it fixed the problem (switch lines 13 and 14) but I’m not sure if it’s the best way to do it.
Thanks!
function setup()
img1 = image(50,50)
fill(0,35,255,127)
setContext(img1)
ellipse(25,25,50)
setContext()
img2 = image(50,50)
for i = 1,50 do
for j = 1,50 do
local r,g,b,a = img1:get(i,j)
local v = 255/a
img2:set(i,j,color(r,g,b,a))
-- img2:set(i,j,color(r*v,g*v,b*v,a))
end
end
end
function draw()
background(40, 40, 50)
noSmooth()
sprite(img1,WIDTH/4,HEIGHT/2,WIDTH/3)
sprite(img2,WIDTH*3/4,HEIGHT/2,WIDTH/3)
end
Something to do with the pre multiplied alpha flag perhaps? If I recall, it is automatically set to true if you use image set, but perhaps you can override this?
You can set img2.premultiplied=true before drawing the image, but that only works in the example. Since I’m copying the data into the rects in the mesh, it saves the wrong value
function setup()
img1 = image(50,50)
fill(0,35,255,127)
setContext(img1)
ellipse(25,25,50)
setContext()
m = mesh()
tab = {}
for i = 1,img1.width do
tab[i] = {}
for j = 1,img1.height do
tab[i][j] = m:addRect(i,j,1,1)
local r,g,b,a = img1:get(i,j)
m:setRectColor(tab[i][j],color(r,g,b,a))
end
end
end
function draw()
background(40, 40, 50)
noSmooth()
sprite(img1,WIDTH/4,HEIGHT/2,WIDTH/3)
pushMatrix()
translate(WIDTH*3/4-WIDTH/6,HEIGHT/2-WIDTH/6)
scale(WIDTH/3/img1.width)
m:draw()
popMatrix()
end
@Dwins I wasn’t trying to solve the problem, I was just showing that adding a background color totally changes the color even though your original color hasn’t changed.