答案是:完全ojbk
python具有强大的图像处理功能,这归功于他 的PIL模块
与我们平时所见的使用PS等软件P图有所不同,python实现的图像处理是以代码的形式完成工作,也是千峰这篇文章要说的。
需要相关学习资料请关注我
操作环境:win7 操作系统 需要安装python2.7以及指定的对应PIL模块
实际操作代码如下:
第一步:图片裁切
from PIL import Image
im = Image.open("jgz.jpg")
box = (10,10,100,100)
region = im.crop(box)
region.save("cutting.jpg")
将jgz.jpg图片的((10,10), (10,100),(100,10),(100,100))所划出的区域进行裁切并保存在cutting.jpg当中
第二步:拼接图片
from PIL import Image
img = Image.open("./background.jpg")
jgz = Image.open("./jgz1.jpg")
img.paste(jgz,(196,139))
img.save("./out.jpg")
将background.jpg当做背景,将jgz1.jpg拼在其上边,位置是(196.139)。并保存为out.jpg
第三步:图片缩放
from PIL import Image
infile = './jgz.jpg'
outfile = './jgz1.jpg'
im = Image.open(infile)
(x,y) = im.size
x_s = 310
y_s = y*x_s/x
out=im.resize((x_s,y_s),Image.ANTIALIAS)
out.save(outfile)
将jpz.jpg的横向像素强制为310,纵横比不变。并保存在jgz1.jpg当中
第四步:在图片上添加文字
#coding=utf-8from PIL import Image, ImageDraw, ImageFont
txt = "你这个死宅说话"
txt2 = " 还挺搞笑的"
font_img = Image.open("./img.jpg")
draw = ImageDraw.Draw(font_img)
ttfront = ImageFont.truetype('./simhei.ttf',55)
draw.text((140,560),unicode(txt,"UTF-8"), fill=(0,0,0), font=ttfront)
draw.text((160,630),unicode(txt2,"UTF-8"), fill=(0,0,0), font=ttfront)
font_img.save("./out.jpg")
保证 simhei.ttf的路径可以找到。在图片 img.jpg的(140,560) (160,630)两个位置分别写入txt 和 txt2这两句汉字。文件编码是utf-8,并另存为out.jpg
第五步:图片alpha通道化,理论上将白色变成透明
from PIL import Image
img = Image.open("jgz.jpg")
img = img.convert("RGBA")
datas = img.getdata()
newData = list()
for item in datas:
if item[0] >220 and item[1] > 220 and item[2] > 220:
newData.append(( 255, 255, 255, 0))
else:
newData.append(item)
img.putdata(newData)
img.save("jgz_alpha.png","PNG")
将jgz.jpg的白色透明化并另存为jgz_alpha.png。注意透明化的图片文件的格式一般为png