Background color when cropping image with PIL
Answer a question
The good thing with PIL.crop is that if we want to crop outside of the image dimensions, it simply works with:
from PIL import Image
img = Image.open("test.jpg")
img.crop((-10, -20, 1000, 500)).save("output.jpg")
Question: how to change the background color of the added region to white (default: black)?

Note:
-
if possible, I'd like to keep
crop, and avoid to have to create a new image and paste the cropped image there like in Crop image, change black area if not not enough photo region in white. -
Here is a download link to original image: https://i.stack.imgur.com/gtA70.jpg (303x341 pixels)
Answers
I think it is not possible with one function call due to the relevant C function which seems to zero-out the destination image memory region (see it here: https://github.com/python-pillow/Pillow/blob/master/src/libImaging/Crop.c#L47)
You mentioned as not interested to create new Image and copy over it but i am pasting that kind of solution anyway for reference:
from PIL import Image
img = Image.open("test.jpg")
x1, y1, x2, y2 = -10, -20, 1000, 500 # cropping coordinates
bg = Image.new('RGB', (x2 - x1, y2 - y1), (255, 255, 255))
bg.paste(img, (-x1, -y1))
bg.save("output.jpg")
Output:

更多推荐

所有评论(0)