python图像压缩函数 python压缩图片像素

opencv python 调用resize函数时一直报错python图像压缩函数你可以重新看一下opencv 的文档,重新理解一下resize函数 。resize函数提供了两种方法来修改图像的大小 , 一种是提供一个目标图像大?。╠size)这和目标大小包含两个维度python图像压缩函数:width和heigth 。换句话说就是我要告诉resize函数我要将图片变为dsize这么大/小 。另一种方式是通过两个参数fx,fy , 这两个参数是缩放比例,分别表示对目标图像的长宽进行缩放的比例 。
python中PLE调整图片大小,等比例压缩文件,怎么写代码How do I read image data from a URL in Python?
importosimportImagefileName ='c:/py/jb51.jpg'fp =open(fileName,'rb')im =Image.open(fp)fp.close()x,y =im.sizeifx 300ory300:os.remove(fileName)
from PIL import Imageimport requestsimport numpy as npfrom StringIO import StringIOresponse = requests.get(url)img = np.array(Image.open(StringIO(response.content)))
from PIL import Imageimport urllib2
im = Image.open(urllib2.urlopen(url))
or if you use requests:
from PIL import Imageimport requests
im = Image.open(requests.get(url, stream=True).raw)
[python] view plain copy
[html] view plain copy
#coding:utf-8
'''
python图片处理
'''
import Image as image
#等比例压缩图片
def resizeImg(**args):
args_key = {'ori_img':'','dst_img':'','dst_w':'','dst_h':'','save_q':75}
arg = {}
for key in args_key:
if key in args:
arg[key] = args[key]
im = image.open(arg['ori_img'])
ori_w,ori_h = im.size
widthRatio = heightRatio = None
ratio = 1
if (ori_w and ori_warg['dst_w']) or (ori_h and ori_harg['dst_h']):
if arg['dst_w'] and ori_warg['dst_w']:
widthRatio = float(arg['dst_w']) / ori_w #正确获取小数的方式
if arg['dst_h'] and ori_harg['dst_h']:
heightRatio = float(arg['dst_h']) / ori_h
if widthRatio and heightRatio:
if widthRatioheightRatio:
ratio = widthRatio
else:
ratio = heightRatio
if widthRatio and not heightRatio:
ratio = widthRatio
if heightRatio and not widthRatio:
ratio = heightRatio
newWidth = int(ori_w * ratio)
newHeight = int(ori_h * ratio)
else:
newWidth = ori_w
newHeight = ori_h
im.resize((newWidth,newHeight),image.ANTIALIAS).save(arg['dst_img'],quality=arg['save_q'])
'''
image.ANTIALIAS还有如下值:
NEAREST: use nearest neighbour
BILINEAR: linear interpolation in a 2x2 environment
BICUBIC:cubic spline interpolation in a 4x4 environment
ANTIALIAS:best down-sizing filter
'''
#裁剪压缩图片
def clipResizeImg(**args):
args_key = {'ori_img':'','dst_img':'','dst_w':'','dst_h':'','save_q':75}
arg = {}
for key in args_key:
if key in args:
arg[key] = args[key]
im = image.open(arg['ori_img'])
ori_w,ori_h = im.size
dst_scale = float(arg['dst_h']) / arg['dst_w'] #目标高宽比
ori_scale = float(ori_h) / ori_w #原高宽比
if ori_scale = dst_scale:
#过高
width = ori_w
height = int(width*dst_scale)
x = 0
y = (ori_h - height) / 3
else:
#过宽
height = ori_h
width = int(height*dst_scale)
x = (ori_w - width) / 2
y = 0
#裁剪
box = (x,y,width+x,height+y)
#这里的参数可以这么认为:从某图的(x,y)坐标开始截,截到(width+x,height+y)坐标
#所包围的图像,crop方法与php中的imagecopy方法大为不一样
newIm = im.crop(box)
im = None
#压缩
ratio = float(arg['dst_w']) / width
newWidth = int(width * ratio)
newHeight = int(height * ratio)
newIm.resize((newWidth,newHeight),image.ANTIALIAS).save(arg['dst_img'],quality=arg['save_q'])
#水印(这里仅为图片水印)

推荐阅读