python图片裁剪、压缩、拼接等操作

tech2025-06-06  11

这里介绍Image模块的使用方法,想了解PIL各模块详细介绍的请点击

打开图片 im = Image.open("E:\mzw.jpg") 显示图片 im.show() 创建副本 (拷贝图片) im_copy = im.copy() 返回指定尺寸的图像的拷贝 region = im.resize((100, 100)) 获取图片文件的大小 # 获取文件大小:KB size = os.path.getsize(im) 获取图片文件的尺寸 im_size = im.size 创建图片 # 创建一个方形红色图片 im = Image.new("RGB", (128, 128), "#FF0000") 裁剪矩形区域 # 定义裁剪区域 box = (100,100,200,200) im_c = im.crop(box) 图像粘贴(加水印) # 将图片im_c 粘贴到 图片im 指定位置 im.paste(im_c,(100,100),None) 颜色通道分离 r,g,b = im.split() r.show() g.show() b.show() 颜色通道合并 im_merge = Image.merge("RGB",[b,r,g]) 查找gif 针图片 im_gif = Image.open("E:\mzw.gif") print(im_gif.mode) im_gif.show() ##第0帧 im_gif.seek(3) im_gif.show() im_gif.seek(9) im_gif.show()

图片 大小 尺寸压缩DEMO

导入包

from PIL import Image import os

获取图片文件的大小

def get_size(file): # 获取文件大小:KB size = os.path.getsize(file) return size / 1024

拼接输出文件地址

def get_outfile(infile, outfile): if outfile: return outfile dir, suffix = os.path.splitext(infile) outfile = '{}-out{}'.format(dir, suffix) return outfile

压缩文件到指定大小

def compress_image(infile, outfile='', mb=150, step=10, quality=80): """不改变图片尺寸压缩到指定大小 :param infile: 压缩源文件 :param outfile: 压缩文件保存地址 :param mb: 压缩目标,KB :param step: 每次调整的压缩比率 :param quality: 初始压缩比率 :return: 压缩文件地址,压缩文件大小 """ o_size = get_size(infile) if o_size <= mb: return infile outfile = get_outfile(infile, outfile) while o_size > mb: im = Image.open(infile) im.save(outfile, quality=quality) if quality - step < 0: break quality -= step o_size = get_size(outfile) return outfile, get_size(outfile)

修改图片尺寸

def resize_image(infile, outfile='', x_s=1376): """修改图片尺寸 :param infile: 图片源文件 :param outfile: 重设尺寸文件保存地址 :param x_s: 设置的宽度 :return: """ im = Image.open(infile) x, y = im.size y_s = int(y * x_s / x) out = im.resize((x_s, y_s), Image.ANTIALIAS) outfile = get_outfile(infile, outfile) out.save(outfile)

图片裁剪

def cropImg(path): # 打开图片 img = Image.open(path) # 获取图片的尺寸长 x = img.size[0] # 获取图片的尺寸宽 y = img.size[1] # 截图 h = 50 cropped = img.crop((0, 0, x, y - h)) # 保存到新的目录中 cropped.save(path)

图片拼接

def join(png1, png2, size): img1, img2 = Image.open(png1), Image.open(png2) size1, size2 = img1.size, img2.size # 获取两张图片的大小 joint = Image.new('RGB', (size1[0], size1[1] + size2[1] - size)) # 新建一张新的图片 # 因为拼接的图片的宽都是一样,所以宽为固定值 # 高为两张图片的高相加再减去需要缩进的部分 loc1, loc2 = (0, 0), (0, size1[1] - size) # 两张图片的位置 # a------------- # | | # | | # | | # | | # | | # b------------| # | | # | | # | | # | | # |------------| # 位置都是以该图片的左上角的坐标决定 # 第一张图片的左上角为a点,a的坐标为(0,0) # 第二张图片的左上角为b点,a的横坐标为0,纵坐标为第一张图片的纵坐标减去第二张图片上移的size: (0, size[1]-size) joint.paste(img2, loc2) joint.paste(img1, loc1) # 因为需要让第一张图片放置在图层的最上面,所以让第一张图片最后最后附着上图片上 joint.save(result)

如果同时有修改尺寸和大小的需要,可以先修改尺寸,再压缩大小

最新回复(0)