[Python] Image simple processing (PIL or Pillow)

Source: Internet
Author: User
Tags transparent watermark

A few days ago to get the Django image upload, upload and need to do some simple processing, Python PIL module is specifically used to do this thing.

So divert do a few common picture operations, recorded here, in order to spare.

Here is a font file, you can choose one in their own system, I put this package in the network disk download


A pattern

Original picture




Action one: thumbnails (usually not in this way, because the picture quality damage is too large)



Action two: Rotate a part of the picture



Action Three: Add a picture watermark to the picture, 2 layers merged



Operation four: To add a text watermark to the picture, this use more, I got a white light down here, can be made completely transparent



Operation V-ratio compression (more suitable for thumbnail images)



Operation six according to the proportion of the cut, and so on compression, sometimes need a proportional picture can do this



Two codes

#-*-Encoding=utf-8-*-"Author:orangleliupil handle pictures, verify, process size, format filter compression, convert picture library best with pillow and a test picture test.jpg, a log picture, A font file ' #图片的基本参数获取try: from PIL import image, Imagedraw, Imagefont, imageenhanceexcept importerror:import image, I Magedraw, Imagefont, Imageenhancedef compress_image (IMG, w=128, h=128): "Thumbnail" img.thumbnail ((w,h)) IM . Save (' test1.png ', ' png ') print U ' successfully saved as PNG format, compressed to 128*128 format Picture ' Def cut_image (img): ' ', rotate, paste ' #eft, upp     Er, right, lower #x y z W x, S is the starting point, z,w is the offset value width, height = img.size box = (width-200, height-100, width, height) Region = img.crop (box) #旋转角度 region = Region.transpose (image.rotate_180) img.paste (Region, Box) Img.save (' Test2.jpg ', ' JPEG ') print U ' re-puzzle success ' Def logo_watermark (IMG, Logo_path): ' Add a picture watermark, the principle is to merge layers, with PNG better ' ba Seim = img Logoim = image.open (logo_path) bw, BH = baseim.size LW, LH = Logoim.size baseim.paste (Logoim, (bw-l W, BH-LH)) Baseim.save (' Test3.jpg', ' JPEG ') print u ' logo watermark combination successful ' Def text_watermark (img, text, out_file= "Test4.jpg", Angle=23, opacity=0.50): ' Add A text watermark, made transparent watermark appearance, should be the PNG layer merge http://www.pythoncentral.io/watermark-images-python-2x/here will produce the famous Importerror ("The _ IMAGINGFT C module is not installed ") error Pillow install to fix pip install Pillow ' watermark = image.new (' RGBA ', img.s                                       Ize, (255,255,255)) FONT = "Msyh.ttf" size = 2 N_font = Imagefont.truetype (font, size) #得到字体 n_width, n_height = n_font.getsize (text) text_box = min (watermark.size[0], watermark.size[1]) W Hile (N_width+n_height < Text_box): size + = 2 N_font = Imagefont.truetype (font, size=size) N_widt H, n_height = n_font.getsize (text) #文字逐渐放大, but smaller than the width-height minimum of the picture Text_width = (watermark.size [0]-N_width)/2 Text_height = (watermark.size[1]-n_height)/2 #watermark = Watermark.resize ((text_width,text_h Eight), Image.antialias) dRaw = Imagedraw.draw (watermark, ' RGBA ') #在水印层加画笔 Draw.text (Text_width,text_heigh T), text, Font=n_font, fill= "#21ACDA") watermark = watermark.rotate (angle, image.bicubic) Alpha = water Mark.split () [3] alpha = imageenhance.brightness (alpha). Enhance (opacity) Watermark.putalpha (Alpha) Image.composite     (Watermark, IMG, watermark). Save (Out_file, ' JPEG ') print U "text watermark succeeded" #等比例压缩图片def resizeimg (IMG, dst_w=0, dst_h=0, qua=85): "Only give the width or height, or two to give, and then take the appropriate proportion if the picture is smaller than the size to compress, do not compress the" ' ori_w, ori_h = im.size WidthRatio = HeightRatio = None ratio = 1 if (Ori_w and Ori_w > Dst_w) or (Ori_h and Ori_h > Dst_h): If Dst_w and Ori_w > DS T_w:widthratio = float (dst_w)/Ori_w #正确获取小数的方式 if Dst_h and Ori_  H > dst_h:heightratio = float (dst_h)/Ori_h if WidthRatio and Heightratio:if widthRatio      < heightratio:          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.R Esize ((newwidth,newheight), Image.antialias). Save ("Test5.jpg", "JPEG", Quality=qua) print U ' etc than compression complete ' ' Image.anti Alias also has the following values: Nearest:use NEAREST neighbour Bilinear:linear interpolation in a 2x2 environment bicubic:cubic Spli NE interpolation in a 4x4 environment antialias:best down-sizing filter "#裁剪压缩图片def clipresizeimg (IM, Dst_w, dst_h , qua=95): "First cut the picture according to a scale, and then compress to a specified size an image 16:5, compression to 2:1 and a width of 200, you must first cut the picture to 10:5, and then in the compression" ori_w, Ori_h = im.size Dst_scale = float (dst_w)/dst_h #目标高宽比 Ori_scale = float (ori_w)/Ori_h #原高宽比 if Ori_scale < = Dst_scale: #过高       width = ori_w height = Int (width/dst_scale) x = 0 y = (ori_h-height)/2 else: #过宽 Height = ori_h width = Int (height*dst_scale) x = (ori_w-width)/2 y = 0 #裁剪 box = (x , Y,width+x,height+y) #这里的参数可以这么认为: Starting with the (x, y) coordinates of a graph, intercept the (width+x,height+y) coordinates #所包围的图像, crop method is quite different from the Imagecopy method in PHP Newi m = im.crop (box) im = None #压缩 ratio = float (dst_w)/width newwidth = Int (width * ratio) newheight = Int (h Eight * ratio) newim.resize ((newwidth,newheight), Image.antialias). Save ("Test6.jpg", "JPEG", quality=95) print "Old s Ize%s%s "% (Ori_w, ori_h) print" New size%s%s "% (Newwidth, newheight) print U" clipped and so on than compression complete "if __name__ = =" __main__ ":" is mainly implemented function, the code is not how to tidy up "' im = Image.open (' test.jpg ') #image object compress_image (IM) im = Image.open (' t Est.jpg ') #image object cut_image (IM) im = Image.open (' test.jpg ') #image object Logo_watermark (IM, ' logo.png ') im =  Image.open (' test.jpg ')#image object Text_watermark (IM, ' orangleliu ') im = Image.open (' test.jpg ') #image object Resizeimg (IM, dst_w=100, qua=85 ) im = Image.open (' test.jpg ') #image object clipresizeimg (IM, 100, 200)


Three references

Http://www.cnblogs.com/way_testlife/archive/2011/04/17/2019013.html
Http://effbot.org/imagingbook/introduction.htm
Http://tech.seety.org/python/python_imaging.html
http://liluo.org/blog/2011/08/python-add-watermark-with-pil/Plus watermark
Several common summary of http://my.oschina.net/neo600/blog/136393
http://oldj.net/article/text-to-image/


This article is from the "Orangleliu Notebook" blog, reproduced please be sure to keep this source http://blog.csdn.net/orangleliu/article/details/43529319

Author Orangleliu using Attribution-NonCommercial-sharing protocol in the same way

[Python] Image simple processing (PIL or Pillow)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.