Scaling image proportional

Share your advanced PureBasic knowledge/code with the community.
User avatar
Lunasole
Addict
Addict
Posts: 1091
Joined: Mon Oct 26, 2015 2:55 am
Location: UA
Contact:

Scaling image proportional

Post by Lunasole »

Another my small old & trivial thing translated to PB when it was required ^^

Code: Select all

EnableExplicit
; some image scaling stuff
;	2016			(c) Lunasole

; used to scale image proportionally
; *res_w/h:		used to return value
; from_ :		original image sizes
; to_	:		wanted image sizes. if 0, *res_ value will be used
; RETURN:		none
Procedure ScaleProportional (*res_w.Integer, *res_h.Integer, from_width, from_heigh, to_width = 0, to_heigh = 0)
	Protected.d hMod
	If Not to_width :	to_width = *res_w\i : EndIf : *res_w\i = to_width
	If Not to_heigh :	to_heigh = *res_h\i : EndIf : *res_h\i = to_heigh
	
	If from_heigh > to_heigh Or from_width > to_width
		hMod = from_width / to_width
		If Not Round(from_heigh / hMod, #PB_Round_Nearest) > to_heigh And Not Round(from_width / hMod, #PB_Round_Nearest) > to_width
		Else
			hMod = from_heigh / to_heigh
		EndIf
		*res_w\i = from_width / hMod		; decrease img
		*res_h\i = from_heigh / hMod
	ElseIf from_heigh < to_heigh Or from_width < to_width
		hMod = to_width / from_width
		If Not Round(from_heigh * hMod, #PB_Round_Nearest) > to_heigh And Not Round(from_width * hMod, #PB_Round_Nearest) > to_width
		Else
			hMod = to_heigh / from_heigh
		EndIf
		*res_w\i = from_width * hMod		; enlarge img
		*res_h\i = from_heigh * hMod
	EndIf
EndProcedure

;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; examples
UseJPEGImageDecoder()
UsePNGImageDecoder()

Define hImg = LoadImage(#PB_Any, #PB_Compiler_Home+"/Examples/Sources/data/purebasic.bmp")
Define resX, resY
Debug "The source resolution is " + ImageWidth(hImg) + "x" + ImageHeight(hImg)
Debug "Scaling up to 800x600..."
ScaleProportional(@resX, @resY, ImageWidth(hImg), ImageHeight(hImg), 800, 600)
Debug "Proportionally scaled to " + resX + "x" + resY
Debug ""
Debug "The source resolution is " + ImageWidth(hImg) + "x" + ImageHeight(hImg)
Debug "Scaling down to 80x60..."
ScaleProportional(@resX, @resY, ImageWidth(hImg), ImageHeight(hImg), 80, 60)
Debug "Proportionally scaled to " + resX + "x" + resY

; after function called you can pass results with ResizeImage() to really resize image :3
ResizeImage(hImg, resX, resY, #PB_Image_Raw)

FreeImage(hImg)
"W̷i̷s̷h̷i̷n̷g o̷n a s̷t̷a̷r"