Page 1 of 1

Image Resize while Maintaining Image Ratio

Posted: Fri Nov 15, 2024 10:04 pm
by Phollyer
Here is a handy image Resizer that Maintains the Image Ratio, but Resizes it to "fit" an ImageGadget to present on the screen.
The default will return Image to the Left of the ImageGadget, optionally you can have the image Centered.

Code: Select all

Procedure ImageResize(SourceImage.i, Width, Height, Center=#False)
  Protected W.i, H.i, Ratio.f, NewImage.i, WC.i, HC.i
  W = ImageWidth(SourceImage)
  H = ImageHeight(SourceImage)
  ;Resize Largest Variance First
  If Abs(Width-W)>Abs(Height-H)
  	W = ImageWidth(SourceImage)
		Ratio = Width / ImageWidth(SourceImage)
		ResizeImage(SourceImage, Width, ImageHeight(SourceImage) *(Ratio))
		H = ImageHeight(SourceImage)
		;Only Other Resize if Bigger
	  If H > Height
  		Ratio = Height / ImageHeight(SourceImage)
  		ResizeImage(SourceImage, ImageWidth(SourceImage) *(Ratio), Height)
  	EndIf
  Else
    H = ImageHeight(SourceImage)
		Ratio = Height / ImageHeight(SourceImage)
		ResizeImage(SourceImage, ImageWidth(SourceImage) *(Ratio), Height)
		W = ImageWidth(SourceImage)
		;Only Other Resize if Bigger
  	If W > Width
  		Ratio = Height / ImageHeight(SourceImage)
  		ResizeImage(SourceImage, ImageWidth(SourceImage) *(Ratio), Height)
  	EndIf
  EndIf
	
  If Center
    WC = (Width - ImageWidth(SourceImage)) / 2
    HC = (Height - ImageHeight(SourceImage)) / 2
    ImageFree(NewImage)
		NewImage = CreateImage(#PB_Any, Width, Height, 32, #PB_Image_Transparent)
		StartDrawing(ImageOutput(NewImage))
  		DrawingMode(#PB_2DDrawing_AlphaBlend)
  		DrawImage(ImageID(SourceImage),WC,HC)
		StopDrawing()
		ImageFree(SourceImage)
		SourceImage = CopyImage(NewImage, #PB_Any)
		FreeImage(NewImage)
	EndIf
	ProcedureReturn SourceImage
EndProcedure