from PIL import Image
def show_info():
im = Image.open("image.jpg")
print(im.mode) # RGB
print(im.format) # JPEG
print(im.size) # (1200, 800)
print(im.filename) # image.jpg
print(im.width) # 1200
print(im.height) # 800
image.jpg
转换图片格式jpg -> png
def convert_format():
Image.open("image.jpg").save("image.png")
im = Image.open("image.png")
print(im.mode) # RGB
print(im.format) # PNG
创建缩略图
def create_thumbnail():
im = Image.open("image.jpg")
im.thumbnail((120, 80))
im.save("image_thumbnail.jpg", "PNG")
image_thumbnail.jpg
裁剪图片def crop_iamge():
im = Image.open("image.jpg")
box = (206, 180, 994, 648) # 左上角和右下角坐标,类似qq截图
region = im.crop(box)
region.save("image_region.jpg")
# 处理子图,旋转180度,粘贴回原图
region = region.transpose(Image.ROTATE_180)
im.paste(region, box)
im.save("image_paste.jpg")
image_region.jpg
image_paste.jpg
def roll_image():
im = Image.open("image_region.jpg")
image = im.copy()
delta = 2
width_half = image.width // delta
box_left = (0, 0, width_half, image.height)
box_right = (width_half, 0, image.width, image.height)
part_left = image.crop(box_left)
part_right = image.crop(box_right)
image.paste(part_left, box_right)
image.paste(part_right, box_left)
image.save("image_roll.jpg")
image_roll.jpg
def split_merge():
im = Image.open("image_region.jpg")
r, g, b = im.split()
print(r, g, b)
r.save("r.jpg")
g.save("g.jpg")
b.save("b.jpg")
image = Image.merge("RGB", (r, g, b))
image.save("image_merge.jpg")
r.jpg
g.jpg
b.jpg
image_merge.jpg
def resize():
im = Image.open("image_region.jpg")
out = im.resize((128, 128))
out.save("image_resize.jpg")
image_resize.jpg
def rotate():
im = Image.open("image_region.jpg")
out = im.rotate(45)
out.save("image_rotate.jpg")
image_rotate.jpg
逆时针
def transpose():
im = Image.open("image_region.jpg")
# 左右镜像
out = im.transpose(Image.FLIP_LEFT_RIGHT)
out.save("image_flip_left_right.jpg")
# 上下镜像
out = im.transpose(Image.FLIP_TOP_BOTTOM)
out.save("image_flip_top_bottom.jpg")
# 旋转90度
out = im.transpose(Image.ROTATE_90)
out.save("image_rotate_90.jpg")
# 旋转180度
out = im.transpose(Image.ROTATE_180)
out.save("image_rotate_180.jpg")
# 旋转270度
out = im.transpose(Image.ROTATE_270)
out.save("image_rotate_270.jpg")
image_flip_left_right.jpg
image_rotate_90.jpg
def convert_l():
im = Image.open('image_region.jpg').convert('L')
im.save("image_l.jpg")
image_l.jpg
from PIL import ImageFilter
def filter():
im = Image.open('image_region.jpg')
im.filter(ImageFilter.DETAIL)
im.save("image_detail.jpg")
image_detail.jpg
im = Image.open('image_region.jpg')
out = im.point(lambda i: i * 1.2)
out.save("image_point.jpg")
image_region.jpg
参考