Get image pixel dimensions

Today I encountered this challenge when a collaborator asked for code that would resize an image label to fit the image’s pixel size.

Unfortunately Roblox does not provide this information, which is honestly insane, but Roblox is a small indie company and we can’t ask for such a complex feature.

Solutions provided online so far are sub-optimal, so I came up with this

--Resizes the selected image label to fit the image's pixel size, paste in the command line and press enter
local imageLabel = game.Selection:Get()[1]
local originalImage = imageLabel.Image

local id = originalImage:match("(%d+)")
local httpService = game:GetService("HttpService")
local PNG = httpService:GetAsync("https://assetdelivery.roproxy.com/v1/asset?id="..id)

local function parseBigEndian(str, index)
    local b1, b2, b3, b4 = string.byte(str, index, index + 3)
    return ((b1 * 256 + b2) * 256 + b3) * 256 + b4
end

local pngSignature = "\137PNG\r\n\26\n"
if PNG:sub(1, 8) ~= pngSignature then
    warn("Invalid PNG signature")
else
    local chunkType = PNG:sub(13, 16)
    if chunkType ~= "IHDR" then
        warn("IHDR chunk not found in PNG")
    else
        local width = parseBigEndian(PNG, 17)
        local height = parseBigEndian(PNG, 21)
        print("Parsed PNG Dimensions: Width =", width, "Height =", height)
        imageLabel.Size = UDim2.new(0, width, 0, height)
    end
end

The code is ugly and was made in a rush, I’ll leave the cleaning to you.
The logic is simple, it downloads the PNG from roblox’s API and parses the PNG’s signature to extract the data. This is better used for studio and should probably be avoided or at the very least only used to bake the data for production.

Remember to enable HTTP requests in settings

Aight I’ll go eat pizza, bye :pizza:

5 Likes

lmao the shade :low_battery::low_battery::low_battery:

but for what reason is that necessary though? does stretch, fit, etc have some quirks?

1 Like

For some applications it’s good to have. Sometimes you just want an image to be sized just right, like when you want to animate its size. Normally you have to look into the file’s data and manually type the numbers into the imagelabel, this saves you that time.

Also this is just generally a faster approach than what is otherwise found online. Some people put in entire web services for this. Services which often go down btw.

1 Like

Crazy claim :sob:

well yeah here’s a much simpler way to do it

local imageAssetId = 'rbxassetid://your id'
local AssetService = game:GetService("AssetService");
local imageSize = AssetService:CreateEditableImageAsync(
    Content.fromUri(imageAssetId)
).Size;

print(imageSize)

Oh cool it’s that new API thingy