Python 練習冊,每天一個小程序-解答

習題來源:
https://github.com/Yixiaohan/show-me-the-code
要學習Python的可以去試着刷下題。
我也是參考着別人的想法,再加上一些自己的思考和分析。希望經過自己的努力,能達到一個更高的水平。
這裏寫圖片描述

分析
題目中涉及到對圖片的處理,就需要用到Python中常用的第三方庫Pillow
對於Pillow的安裝和使用,可以參考
http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014320027235877860c87af5544f25a8deeb55141d60c5000

#! usr/bin/env python
# 載入模塊
from PIL imort Image, ImageDraw, ImageFont

image = Image.open('test.jpg') # 打開圖像
draw = ImageDraw.Draw(image)  #  ImageDraw module creates drawing surface for image 創建繪畫對象 #注(a)
addfont = ImageFont.truetype("arial.ttf", size=40)# 注(b)
width, height = image.size
draw.text((width-50, 0), '99', font=myfont, fill=(255, 0, 0)) #注(a)
image.show() # 顯示
# image.save('result.jpg', 'jpeg') # 保存

這裏寫圖片描述


Pillow官方文檔
https://pillow.readthedocs.org/

(a)ImageDraw Module
The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.(該模塊給圖像提供了圖形化處理,可以利用該模塊創建一個新的圖像,然後可以在新圖像上進行註釋修整等)

常見的Function:
class PIL.ImageDraw.Draw(im, mode=None)

功能:Creates an object that can be used to draw in the given image.
     (該函數創建了一個對象,可以在給定圖像上進行畫圖)
參數: im : 要處理的圖片
      mode ;圖像顏色值的可選模式,如果省略,默認模式圖像的模式。一般的是省略。       

常用Method
(1)PIL.ImageDraw.Draw.text(xy, text, fill=None, font=None, anchor=None, spacing=0, align="left")

功能: Draws the string at the given position(在給定位置畫上String符號)
參數:xy – Top left corner of the text. (text的左上角)
          If it contains anynewline characters, the text is passed  
          on to multiline_text(),如果包含換行符,則使用multiline_text()
     text – Text to be drawn. 需要被畫在圖像上的文本
     fill - 填充顏色
     font -字體
     spacing – If the text is passed on to multiline_text(), the
               number of pixels between lines.
     align – If the text is passed on to multiline_text(), 
              “left”, “center” or “right” 

(2)PIL.ImageDraw.Draw.multiline_text(xy, text, fill=None, font=None, anchor=None, spacing=0, align="left")
與(1)類似

(b)ImageFont Module

The ImageFont module defines a class with the same name. Instances of this class store bitmap fonts, and are used with the PIL.ImageDraw.Draw.text() method.
定義了相同名字的類,這個類的實例存儲的是位圖字體。常常和PIL.ImageDraw.Draw.text() method一起使用。

Functions:
(1)PIL.ImageFont.load(filename)

This function loads a font object from the given bitmap font file, and returns the corresponding font object.
載入字體。從給定的位圖字體文件載入字體對象。
參數: filename – Name of font file.

(2)PIL.ImageFont.truetype(font=None, size=10, index=0, encoding='')

加載一個TrueType或OpenType字體文件,並創建一個字體對象.
參數:font- 字體文件。在win下會自動去Font目錄下尋找
     size- 字體大小
     index- Which font face to load (default is first available face??(不理解)
     encoding --字體編碼。Unicode(默認)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章