#! Python3#resizeandaddlogo.py-resizes all images in current working directory to fit#in a 300x300 square, and adds catlogo.png to the lower-right corner.ImportOS fromPILImportImageos.chdir ('c:\\users\\administrator\\python35-32\\test\\kuaisu\\ Sci Fi') #设置文件路径SQUARE_FIT_SIZE= #设置图片修改大小logo_size=80 #设置LOGO大小, the original is 800 pixels, too big, set to 80Logo_filename='Catlogo.png'Logoim=Image.open (logo_filename) Logoim=logoim.resize ((logo_size, logo_size)) Logowidth, Logoheight=LogoIm.sizeos.makedirs ('Withlogo', exist_ok=True)#Loop over all files in the working directory. forFileNameinchOs.listdir ('.'): if not(Filename.endswith ('. PNG')orFilename.endswith ('. jpg') orFilename.endswith ('. PNG')orFilename.endswith ('. JPG')) orfilename = =Logo_filename:Continue #Skip Non-image files and the logo file itselfim=image.open (filename) im= Im.convert ('RGB') width, height=im.size#Check If image needs to is resized. ifWidth > Square_fit_size andHeight >square_fit_size:#Calculate The new width and height to resize. ifWidth >Height:height= Int ((square_fit_size/width) *height) Width=square_fit_sizeElse: Width= Int ((square_fit_size/height) *width) Height=square_fit_size#Resize the image. Print('Resizing%s ...'%(filename)) Im=im.resize ((width, height))#ADD logo. ifMin (width, height) >=Int (logo_size):Print('Adding logo to%s ...'%( filename)) Im.paste (Logoim, (width-Logowidth, Height-logoheight), Logoim)#Save changes.Im.save (Os.path.join ('Withlogo', filename))
Python Programming Quick Start 15th Chapter Practical Project Reference Answer (17.7.1)