Average color finder

I do know that editable images are still in beta but this is when they come out of beta and therefore people can use this module.

Hello people of the internet, I am back with another terrible resource!

Anyways here is the module:

local AvgColorFinder = {}
function AvgColorFinder.GetAverageColor(Image:string,Size:Vector2)
	local EI = game:GetService("AssetService"):CreateEditableImageAsync(Image) 	EI.Size = Size EI = EI:ReadPixels(Vector2.zero,Size)
	local r,g,b = 0,0,0
	for i = 1,#EI,4 do r,g,b = r+EI[i],g+EI[i+1],b+EI[i+2] end
	return Color3.new(r/(#EI/4),g/(#EI/4),b/(#EI/4))
end
return AvgColorFinder

Yes, this is that small! In only 8 lines!

Or, if you prefer cleanliness then:

local AvgColorFinder = {}

local AssetService = game:GetService("AssetService")

function AvgColorFinder.GetAverageColor(Image:string,Size:Vector2)
	local EI = AssetService:CreateEditableImageAsync(Image)
	EI.Size = Size
	local r,g,b = 0,0,0
	local col = EI:ReadPixels(Vector2.zero,Size)
	local cols = {}
	for i = 1,#col,4 do
		local r0,g0,b0 = col[i],col[i+1],col[i+2]
		r += r0
		g += g0
		b += b0
	end
	r = r/(#EI/4)
	g = g/(#EI/4)
	b = b/(#EI/4)
	local Color = Color3.new(r,g,b)
	EI:Destroy()
	
	return Color
end

return AvgColorFinder

Thanks to @kalabgs for showing me how I can optimize my code.

  • Great job on this.
  • Eh. (Tell me why?)
  • Bad (Tell me how it’s bad or else your just jealous [of my scripting skillz])

0 voters

Okay, bye bye :3

A model for testing purposes.

3 Likes

It’s not bad but there are some stuff that you could optimize

local AvgColorFinder = {}

local AssetService = game:GetService("AssetService")

function AvgColorFinder.GetAverageColor(Image: string, Size: Vector2)
	local EI = AssetService:CreateEditableImageAsync(Image)
	EI.Size = Size

	local PixelData = EI:ReadPixels(Vector2.zero,Size)
	local r,g,b = 0,0,0
 	local Pixels = #PixelData / 4

	for i = 1, #col, 4 do
		r,g,b = r + PixelData[i], g + PixelData[i + 1], b + PixelData[i + 2]
	end

	local Color = Color3.new(r / Pixels, g / Pixels, b / Pixels)

	EI:Destroy()
	
	return Color
end

return AvgColorFinder
1 Like

Not really optimization but you just cleaned up the code. :confused: I appreciate the gesture doe!

For peformance, instead of looping through every pixel, you could only use every 6 or whatever pixels and still get a good result

1 Like

This is actually very performant friendly so using that tactic would work but I’d rather use this as this also gives a sweet 60 fps. I remember my old version giving me 1 fps because I looped through EVERY possible pixel.

I might be a little dumb, but how do we get the size of the image? It seems you’ve provided presets with both the Image ID and Size. How would we go about getting the size?

Take the image and put it in an image label. Set the scale type to “Slice”. Then click on the slicecenter property and there you will see the image size.

1 Like