Lua image sizing

Date: 2016-07-04
local ImHelper = {}

function ImHelper.getImageSize(currentSize, maxSize, scaleUp)
	local newSize = { currentSize[1], currentSize[2] };

	local ratioX = maxSize[1] / currentSize[1];
	local ratioY = maxSize[2] / currentSize[2];
	local ratio = math.min(ratioX, ratioY);

	if (ratio < 1.0 or scaleUp) then			
		newSize[1] = math.floor(currentSize[1] * ratio) or 0;
		newSize[2] = math.floor(currentSize[2] * ratio) or 0;
	end			
	
	return newSize;
end

function ImHelper.getMinImageSizeToFit(currentSize, targetSize)
	--assert(type(currentSize) == 'table', 'Arg 1: Not a table')
	--assert(#currentSize == 2, 'Arg 1: Invalid size')
	local newSize = currentSize;

	local ratioX = targetSize[1] / currentSize[1];
	local ratioY = targetSize[2] / currentSize[2];
	local ratio = math.max(ratioX, ratioY);
	
	newSize[1] = math.floor(currentSize[1] * ratio) or 0;
	newSize[2] = math.floor(currentSize[2] * ratio) or 0;
	
	return newSize;
end

print( unpack(ImHelper.getImageSize({ 800, 600 }, {200, 200})) )
print( unpack(ImHelper.getMinImageSizeToFit({ 800, 600 }, {200, 250})) )
2370cookie-checkLua image sizing