Reputation: 47
I have a list of images 512 x 512 pixels. I need to make only 32 pixels of every image transparent (from every side), so I can combine those images together into a mosaic. I've found how to change the opacity of the whole image, but not the border. I would be happy with any help!
Here is my code for changing the opacity
for item in dem_fps:
img = Image.open(item)
img.putalpha(127)
Upvotes: 0
Views: 1951
Reputation: 208003
As you want the same alpha/transparency channel in all images, I would tend to want to make it once up front, outside the loop, then simply push it into each image.
from PIL import Image, ImageOps
# Make a single alpha channel in advance = 512x512 black and 448x448 white square in middle
border = 32
alpha = Image.new('L', (512-2*border,512-2*border), "white")
alpha = ImageOps.expand(alpha, border)
alpha.save('DEBUG-alpha.png')
And your code then becomes very simply:
dem_fps = ["1.png", "2.png", "3.png"]
# Open each image in turn and push in our ready-made alpha channel
for item in dem_fps:
im = Image.open(item).convert('RGB')
im.putalpha(alpha)
im.save(f'RESULT-{item}')
The alpha channel (DEBUG-alpha.png
) looks like this:
Of course, you could equally construct the alpha channel by making a 512x512 black square and drawing a white rectangle in the middle if that is conceptually easier for you.
Upvotes: 0
Reputation: 587
Create a copy of image you need to keep for 100% opacity. Put the opacity to the main image, and at last, paste the copied image to the original image. Opacity at the border done.
from PIL import Image
padding = 32
opacity = 127
img = Image.open("image.png").convert('RGBA')
x, y, w, h = padding, padding, img.width - padding, img.height - padding
img_cropped = img.crop((x, y, w, h))
img.putalpha(127)
img.paste(img_cropped, (x, y))
img.save('image_new.png')
Upvotes: 1
Reputation: 337
img = Image.open(‘image.png’)
rgba = img.convert(“RGBA”)
data = rgba.load()
data[0,0]=(data[0,0][0],data[0,0][1],data[0,0][2],127)
img.save(filename)
This code first converts the image to RGBA, which allows us to modify the alpha (a) channel, that determines the transparency of an image. The image is loaded into an array, where it is easier to read and modify pixel values. This code only modifies the pixel at (0,0) ,but you can put it in a loop to modify the pixels on the border of your image.
EDIT - This should work -
for y in range(img.height):
for x in range(img.width):
if any([x<32,x>img.width-32,y<32,y>img.height-32]):
lo[x,y]=(lo[x,y][0],lo[x,y][1],lo[x,y][2],127)
Input -
Output -
Upvotes: 1