3

请教一个关于 Python 绘图的问题,我写了一段代码,随机挑选一张图片给图片中间加上一...

 1 year ago
source link: https://www.v2ex.com/t/901271
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  问与答

请教一个关于 Python 绘图的问题,我写了一段代码,随机挑选一张图片给图片中间加上一个半透明的黑色正方形,但是最后生成的图片中间黑色的正方形都是不透明的。 这是哪里出问题?了

  y4nssss · 1 小时 30 分钟前 · 182 次点击
import os
import random
from PIL import Image, ImageDraw

# 随机选择当前目录中的一张图片
image_files = [f for f in os.listdir('.') if f.endswith('.jpg')]
image_file = random.choice(image_files)

# 缩放图片
im = Image.open(image_file)
im = im.resize((900, 383))

# 创建 ImageDraw 对象,用于绘制图形
draw = ImageDraw.Draw(im)

# 绘制黑色正方形
x = im.width // 2 - 150
y = im.height // 2 - 150
draw.rectangle((x, y, x + 300, y + 300), fill='black')

# 绘制白色边框
draw.rectangle((x, y, x + 300, y + 300), outline='white')

# 创建 000 文件夹
if not os.path.exists('000'):
os.mkdir('000')

# 保存图片到 000 文件夹
im.save(os.path.join('000', image_file))

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK