'Manipulating whole image by moving a pixel in PIL

I was wondering if there is a way to move a pixel from point B to A, and then everything left of this pixel, assuming B is to the right of A, is condensed in the image, and everything to the right would be stretched. Thanks in advance.



Solution 1:[1]

There's not really any "moving" involved. Let's say we start with this image and we are going to stretch everything to the left of the blue line at x=200 till it meets the magenta line, and squidge everything right of the magenta line at x=400 so it fits the remaining space:

enter image description here

#!/usr/bin/env python3

from PIL import Image

# Load original and ensure RGB
# Original created with ImageMagick using:
# magick -fill yellow -background black -size 600x100 label:"Some squidgy text" image.png
im = Image.open('image.png').convert('RGB')

# We are going to stretch everything left of x=200 to x=400 and squidge everything from x=200 to x=400
A, B = 200, 400
# Get left and right part of original image
Lorig = im.crop((0,0,A,im.height))
Rorig = im.crop((A,0,im.width,im.height))

# Stretch left and squidge right
Lnew = Lorig.resize((B,im.height))
Rnew = Rorig.resize((im.width-B,im.height))

# Copy original and splat new left and right parts on top
res = im.copy()
res.paste(Lnew,(0,0))
res.paste(Rnew,(B,0))

# Save result
res.save('result.png')

enter image description here

Note that you could combine the extraction and stretching into one operation, I just chose not to for pedagogical reasons.

Here's an animation for extra fun:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1