PIL之基础应用
>>> from PIL import Image >>> #读取图像文件 ... >>> gal=Image.open('/Users/similarface/PycharmProjects/mybook/products/2016/06/13/1_TIBX78J.png') >>> #查看文件大小 ... >>> gal.size (100, 100) >>> #显示文件 ... >>> gal.show()
>>> #显示灰度图像 ... >>> gal.convert('L').show()
>>> gal.mode 'RGBA' >>> gal.format 'PNG'
''' 将图片的格式转化成jpg格式的 ''' filelist=[] for infile in filelist: f, e = os.path.splitext(infile) outfile = f + ".jpg" if infile != outfile: try: Image.open(infile).save(outfile) except IOError: print "cannot convert", infile ''' 将图片生成缩略图 ''' size = 128, 128 for infile in sys.argv[1:]: outfile = os.path.splitext(infile)[0] + ".thumbnail" if infile != outfile: try: im = Image.open(infile) im.thumbnail(size) im.save(outfile, "JPEG") except IOError: print "cannot create thumbnail for", infile
#获取文件基础消息
import Image for infile in filelist: try: im = Image.open(infile) print infile, im.format, "%dx%d" % im.size, im.mode except IOError: pass
''' Cutting, Pasting and Merging Images # ''' >>> box=(0,25,70,50) >>> region=gal.crop(box) >>> region.show() #存储的图片是从原始文件左上角为参照原点(0,25)开始 #70长 50高的图片 #将图片旋转180 region=region.transpose(Image.ROTATE_180) >>> region.save('/tmp/sub.png',"PNG") def roll(image, delta): "Roll an image sideways" xsize, ysize = image.size delta = delta % xsize if delta == 0: return image #图像裁减 part1 = image.crop((0, 0, delta, ysize)) part2 = image.crop((delta, 0, xsize, ysize)) #图像粘贴 image.paste(part2, (0, 0, xsize-delta, ysize)) image.paste(part1, (xsize-delta, 0, xsize, ysize)) return image #将颜色通道分割 [这儿是rgba的图像格式,有rgb的] r,g,b ,a= gal.split() #合并通道 im = Image.merge("RGB", (b, g, r)) im.show() im = Image.merge("RGB", (b, g, a)) >>> gal=Image.open('/Users/similarface/PycharmProjects/mybook/products/2016/06/13/1_TIBX78J.png') >>> >>> gal.resize((128,128)) <PIL.Image.Image image mode=RGBA size=128x128 at 0x108AECF90> #重新设置大大 >>> gal.resize((1128,1128)).show() #旋转45度 >>> gal.rotate(45).show() #旋转30度 >>> gal.rotate(30).show() #图像左右对称图 gal.transpose(Image.FLIP_LEFT_RIGHT).show() #图像上下对称图 gal.transpose(Image.FLIP_TOP_BOTTOM) #图像旋转 out = im.transpose(Image.ROTATE_90) out = im.transpose(Image.ROTATE_180) out = im.transpose(Image.ROTATE_270)