How to crop center of an image?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By mohsenisaei

When I use “crop” command for an image, that crops top and left of Image…
How can I crop center of this image?
My project:

func _ready():
   yield(VisualServer, "frame_post_draw")
   var img = $ViewportContainer/Viewport.get_texture().get_data()
   img.convert(Image.FORMAT_RGBA8) #The default format doesn't supported alpha
   img.crop(100, 100)
   for x in 100:
	   for y in 100:
		   if (pow(x-49.5, 2) + pow(y-49.5, 2)) / pow(50, 2) > 1:
		   	   img.set_pixel(x, y, Color(0, 0, 0, 0))
:bust_in_silhouette: Reply From: jgodfrey

One way would be to use the blit_rect method, which lets you define a rectangle to be extracted from the source image.

Can you give an example?

mohsenisaei | 2022-08-10 07:42

Here’s a snippet from a larger body of working code. While it won’t work “as-is” (it makes a few var references that aren’t in the small snippet), it should give you an idea of how to use it.

var imgTmp =
imgTmp.create(_screen_size.x, _screen_size.y, false, img.get_format())
imgTmp.blit_rect(img, Rect2(0, 0, x, y), loc)

So, in the above:

  • img is the original, source image
  • imgTmp is a new image to store the cropped version of img

Basically, it does this:

  • create a new image for storage of the cropped data
  • set the size of the cropped image appropriately, and set its format to match the original image
  • extracts a defined rectangle from the source image and places it in the cropped image.

jgodfrey | 2022-08-10 13:56