Excerpt from: Https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 0014320027235877860c87af5544f25a8deeb55141d60c5000
Installing Pillow
Install directly from the PIP at the command line:
$ pip Install Pillow
If you encounter an Permission denied installation failure, add a sudo retry.
manipulating Images
To see the most common image scaling operations, just three or four lines of code:
fromPILImportImage#open a JPG image file, note the current path:im = Image.open ('test.jpg')#Get image size:W, h =im.sizePrint('Original image size:%sx%s'%(W, h))#Zoom to 50%:Im.thumbnail (W//2, H//2))Print('Resize image to:%sx%s'% (W//2, H//2))#Save the scaled image in JPEG format:Im.save ('thumbnail.jpg','JPEG')
Other features such as slicing, rotating, filters, output text, color palettes, and more.
For example, the blur effect also requires just a few lines of code:
from Import Image, ImageFilter # open a JPG image file, note that the current path is im = Image.open ('test1.jpg')# Apply Blur filter:im2 = im.filter (imagefilter.blur) im2.save ('blur.jpg' ' JPEG ')
Effect:
PiL ImageDraw provides a series of drawing methods so that we can draw directly. For example, to generate a letter Captcha image:
fromPILImportImage, Imagedraw, Imagefont, ImageFilterImportRandom#Random Letters:defRndchar ():returnChr (Random.randint (65, 90))#random color 1:defRndcolor ():return(Random.randint (255), Random.randint (255), Random.randint (64, 255))#Random color 2:defRndColor2 ():return(Random.randint (127), Random.randint (127), Random.randint (32, 127))#x:width = 60 * 4Height= 60Image= Image.new ('RGB', (width, height), (255, 255, 255))#To Create a Font object:Font = Imagefont.truetype ('Arial.ttf', 36)#To create a draw object:Draw =Imagedraw.draw (image)#fill each pixel: forXinchRange (width): forYinchRange (height): Draw.point ((x, y), fill=Rndcolor ())#Output Text: forTinchRange (4): Draw.text ((* t + ten, Rndchar (), Font=font, fill=RndColor2 ())#Blur:Image =Image.filter (Imagefilter.blur) Image.Save ('code.jpg','JPEG')
We fill the background with random color, then draw the text, and finally blur the image, get the captcha image as follows:
If you run an error:
IOError: cannot open resource
This is because PiL cannot navigate to the location of the font file and can provide an absolute path based on the operating system, such as:
' C:/windows/winsxs/amd64_microsoft-windows-font /arial.ttf '
To learn more about the powerful features of PiL, please refer to the Pillow official documentation:
https://pillow.readthedocs.org/
Summary
PIL provides a powerful function of manipulating images, which can be done with simple code to complete complex image processing.
Python Learning Notes (42) third-party module (PIL) image processing