- I want to create a python script which searches for all .png images in the current direction. Then create a .jpg file for each .png image.
- The .jpg file should have the same name as the .png file and a width of 800px and a height of 800px. The .png image should be placed in the center of the .jpg image.
- Create a folder with the same name and move the .png image and the .jpg image into this folder.
The problem of my script is that the transparency of the .png is lost. The result is that there is a big black border around the png images after they are placed in the jpg image. How can i get rid of this strange behavior?
Before: [File "1.png"] [File "2.png"]
After: [Folder "1"] [Folder "2"]
Content of [Folder "1"]: [File "1.png"] [File "1.jpg"]
Thats what ive done so far:
` import os from PIL import Image
#Search for all .png images in the current directory
for filename in os.listdir("."):
if filename.endswith(".png"):
# Open the .png image
image = Image.open(filename)
# Get the original size of the image
width, height = image.size
# Create a .jpg image with a width of 800px and a height of 800px
jpg_image = Image.new("RGB", (800, 800), (255, 255, 255))
# Calculate the new x and y position to place the .png image in the center of the .jpg image
x = (800 - width) // 2
y = (800 - height) // 2
# Place the .png image in the center of the .jpg image
jpg_image.paste(image, (x, y))
# Save the .jpg image
jpg_filename = filename.replace(".png", ".jpg")
jpg_image.save(jpg_filename)
# Create a folder with the same name as the .png image
folder_name = filename.replace(".png", "")
if not os.path.exists(folder_name):
os.makedirs(folder_name)
# Move the .png image and the .jpg image into the folder
os.rename(filename, folder_name + "/" + filename)
os.rename(jpg_filename, folder_name + "/" + jpg_filename)`