from PIL import Image
def crop_texture(image_path, texture_rect, texture_rect_offset, output_path):
"""
Crops a portion of the image based on textureRect and textureRectOffset.
:param image_path: Path to the input PNG file.
:param texture_rect: A tuple (x, y, width, height) representing the area to crop.
:param texture_rect_offset: A tuple (offset_x, offset_y) to apply an offset to the texture.
:param output_path: Path where the cropped image will be saved.
"""
# Open the image
img = Image.open(image_path)
# Extract textureRect and textureRectOffset values
x, y, width, height = texture_rect
offset_x, offset_y = texture_rect_offset
# Adjust the coordinates by applying the offset
x += offset_x
y += offset_y
# Flip the y-coordinate relative to the image height
y = img.height - y - height # Flip the y-axis for bottom-left origin
# Define the box to crop (left, upper, right, lower)
crop_box = (x, y, x + width, y + height)
# Crop the image using the adjusted coordinates
cropped_img = img.crop(crop_box)
# Save the cropped image to the output path
cropped_img.save(output_path)
print(f"Cropped image saved to {output_path}")
Example usage
image_path = "Human_Template.png" # Path to your PNG file
texture_rect = (818.0129, 125.0781, 22.911, 44.8) # Example texture rectangle (x, y, width, height)
texture_rect_offset = (0, 0) # Example offset (offset_x, offset_y)
output_path = "output_image.png" # Path to save the cropped image