Skip to content

Instantly share code, notes, and snippets.

@Lincest
Last active August 20, 2020 15:22
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Lincest/c5dddae93b93cfc125afa7f9d40d3953 to your computer and use it in GitHub Desktop.
将图片填充成正方形白底( 发微博? )
from PIL import Image
import os
# JPG文件
def jpg_square(im, min_size=256, fill_color=(255, 255, 255)):
x, y = im.size
size = max(min_size, x, y)
new_im = Image.new('RGB', (size, size), fill_color)
new_im.paste(im, (int((size - x) / 2), int((size - y) / 2)))
return new_im
# PNG文件
def png_square(im, min_size=256, fill_color=(255, 255, 255, 255)):
x, y = im.size
size = max(min_size, x, y)
new_im = Image.new('RGBA', (size, size), fill_color)
new_im.paste(im, (int((size - x) / 2), int((size - y) / 2)))
return new_im
# 获取当前文件夹下所有图片文件->列表
def get_img_file(file_name):
imagelist = []
for parent, dirnames, filenames in os.walk(file_name):
for filename in filenames:
if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
imagelist.append(os.path.join(parent, filename))
return imagelist
if __name__ == '__main__':
picList = get_img_file('./')
if not os.path.exists('./square'):
os.makedirs('./square')
print("处理中...")
for pics in picList:
try:
img = Image.open(pics)
if (pics.endswith('.jpg') or pics.endswith('.jpeg')):
newpic = jpg_square(img)
newpic.save("./square" + pics.strip('.'))
else:
newpic = png_square(img)
newpic.save("./square" + pics.strip('.'))
print(pics + "转换完毕")
except Exception as e:
print("-------------" + pics + "转换失败 -------------")
continue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment