from PIL import Image
import Image
import shutil
import os
class Graphics:
infile = 'D:\\myimg.jpg'
outfile = 'D:\\adjust_img.jpg'
@classmethod
def fixed_size(cls, width, height):
"""按照固定尺寸处理图片"""
im = Image.open(cls.infile)
out = im.resize((width, height),Image.ANTIALIAS)
out.save(cls.outfile)
@classmethod
def resize_by_width(cls, w_divide_h):
"""按照宽度进行所需比例缩放"""
im = Image.open(cls.infile)
(x, y) = im.size
x_s = x
y_s = x/w_divide_h
out = im.resize((x_s, y_s), Image.ANTIALIAS)
out.save(cls.outfile)
@classmethod
def resize_by_height(cls, w_divide_h):
"""按照高度进行所需比例缩放"""
im = Image.open(cls.infile)
(x, y) = im.size
x_s = y*w_divide_h
y_s = y
out = im.resize((x_s, y_s), Image.ANTIALIAS)
out.save(cls.outfile)
@classmethod
def resize_by_size(cls, size):
"""按照生成图片文件大小进行处理(单位KB)"""
size *= 1024
im = Image.open(cls.infile)
size_tmp = os.path.getsize(cls.infile)
q = 100
while size_tmp > size and q > 0:
print q
out = im.resize(im.size, Image.ANTIALIAS)
out.save(cls.outfile, quality=q)
size_tmp = os.path.getsize(cls.outfile)
q -= 5
if q == 100:
shutil.copy(cls.infile, cls.outfile)
@classmethod
def cut_by_ratio(cls, width, height):
"""按照图片长宽比进行分割"""
im = Image.open(cls.infile)
width = float(width)
height = float(height)
(x, y) = im.size
if width > height:
region = (0, int((y-(y * (height / width)))/2), x, int((y+(y * (height / width)))/2))
elif width < height:
region = (int((x-(x * (width / height)))/2), 0, int((x+(x * (width / height)))/2), y)
else:
region = (0, 0, x, y)
crop_img = im.crop(region)
crop_img.save(cls.outfile)
参考:
- Python图像处理库PIL的Image模块介绍(四)
- Python实现图片裁剪的两种方式——Pillow和OpenCV
- python(pil)图像处理(等比例压缩、裁剪压缩) 缩略(水印)图
- Python中用PIL/Pillow裁剪图片
- Python图片裁剪(如: 头像裁剪)
- 用python简单处理图片(2):图像通道\几何变换\裁剪
- 麻烦使用python PIL库裁剪和保存图像
- html img图片等比例缩放
- python图像处理——图像形变与缩放
- Python 图片尺寸缩放的4种方式
- python按照比例缩小图片并生成新的图片
- 图片在IE能正常显示但是不能在Firefox中显示
- Python中的图像处理