Best way to crop images to particular aspect ratio?

So I have a folder full of images, I need to crop them to 3:2 aspect ratio.

I managed to create a code and used the Invoke code activity, that seems to do the job but not in a way I want it.

Dim originalImage As New Bitmap(OriginalImage)

' Calculate the new width and height for a 3:2 aspect ratio
Dim newWidth As Integer = CInt(originalImage.Height * 3 / 2)
Dim newHeight As Integer = CInt(originalImage.Height)

' Create a new bitmap with the calculated dimensions
Dim croppedImage As New Bitmap(newWidth, newHeight)

' Create a graphics object and draw the original image onto the new bitmap
Using g As Graphics = Graphics.FromImage(croppedImage)
    g.DrawImage(originalImage, New Rectangle(0, 0, newWidth, newHeight), New Rectangle(0, 0, originalImage.Width, originalImage.Height), GraphicsUnit.Pixel)
End Using

' Set compression quality (0-100, where 100 is best quality)
Dim quality As Integer = 90

' Save the cropped image with compression
croppedImage.Save(CroppedImage, Imaging.ImageFormat.Jpeg)

Here OriginalImage & CroppedImage are two arguments.

The problem with the code:

  1. Instead of cropping it is directly changing the image size by stretching and thickening, and then the image is looking ugly.
  2. It’s not letting me save it to the same image file, bound to create a copy.

Can anyone help with another way or fix my code? TIA

Hi,

The following sample may help you. (UiPath.Core.Image,SimpleCrop method is used.)

Sample20231225-2.zip (3.6 KB)

Regards,

2 Likes

Hi! Thank you so much, never knew we can do it this way. The only problem seems to be, it’s not letting me overwrite the original image, When I tried putting the same path to save the original image, it’s failing. Can we do it?

Otherwise, this also helping me compress the image size which is a great thing for me.

Hi,

How about the following?

Sample20231225-2 (2).zip (3.2 KB)

Regards,

1 Like

Thank you so much, mate. Now this is working like a charm. Means a lot. :orange_heart:

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.