如果是jpg的话,可以通过改变图片的质量来调节文件的大小。
比如
im = Image.open("aa.JPG")
print im.format, im.size, im.mode
print im.size[0]
im.resize((720,540), Image.ANTIALIAS).save('a.jpg', quality = 95)
你也可以做一个循环,对生成的文件大小与目标大小做比较,直到满足条件为止。
只是给个思路,也许帮不上忙。
可以使用Python中的Pillow库来实现对图片的处理,具体实现步骤如下:from PIL import Image
import os
def process_image(image_path):
'''
对指定路径的图片进行处理
'''
try:
with Image.open(image_path) as img:
# 剔除单通道或无效图片
if img.mode == 'L' or img.mode == 'P' or img.mode == 'RGBA' or img.mode == 'CMYK':
raise Exception('invalid image')
# 更改图片格式
img = img.convert('RGB')
# 调整图片大小
img = img.resize((600, 800), Image.BICUBIC)
img.save(image_path[:-3] + 'jpg')
print('Processed: {}'.format(image_path))
except Exception as e:
# 处理 *** 作中出现的异常
print('Error processing {}: {}'.format(image_path, e))
os.remove(image_path)
def process_images_in_folder(folder_path):
'''
对指定文件夹中的所有图片进行处理
'''
for root, dirs, files in os.walk(folder_path):
for filename in files:
# 只处理.jpg和.jpeg格式的图片
if filename.endswith('.jpg') or filename.endswith('.jpeg'):
image_path = os.path.join(root, filename)
process_image(image_path)
process_images_in_folder('/path/to/folder/')
上述代码可以实现对指定文件夹中所有.jpg和.jpeg格式的图片进行处理,具体处理 *** 作包括剔除单通道或无效图片、更改图片格式、调整图片大小、统一使用600 * 800像素大小以及只使用.jpg格式的图片。
python有一个图像处理库——PIL,可以处理图像文件。PIL提供了功能丰富的方法,比如格式转换、旋转、裁剪、改变尺寸、像素处理、图片合并等等等等,非常强大。举个简单的例子,调整图片的大小:
12345678910111213141516171819
import Image infile = 'D:\\original_img.jpg'outfile = 'D:\\adjust_img.jpg'im = Image.open(infile)(x,y) = im.size #read image sizex_s = 250 #define standard widthy_s = y * x_s / x #calc height based on standard widthout = im.resize((x_s,y_s),Image.ANTIALIAS) #resize image with high-qualityout.save(outfile) print 'original size: ',x,yprint 'adjust size: ',x_s,y_s '''OUTPUT:original size: 500 358adjust size: 250 179'''
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)