當前位置: 妍妍網 > 碼農

Python玩轉PIL庫

2024-02-11碼農

大家好!今天給你們帶來了pillow的簡單玩法。

安裝:

pip install pillow

1.畫出一個4k分辨率圓形:

from PIL import Image, ImageDraw#建立一個透明背景的 4K 影像image = Image.new('RGBA', (3840, 2160), (0, 0, 0, 0))#建立一個畫筆draw = ImageDraw.Draw(image)#繪制一個藍色的圓形#定義圓形外接矩形的左上角和右下角座標#讓外接矩形為正方形即可畫出圓形center_coordinates = (1920, 1080)radius = 500bounding_box = (center_coordinates[0] - radius, center_coordinates[1] - radius, center_coordinates[0] + radius, center_coordinates[1] + radius)#使用畫筆繪制圓形,填充顏色為藍色,透明度為 255draw.ellipse(bounding_box, fill=(0, 0, 255, 255))#顯示影像image.show()

2.三角形

from PIL import Image, ImageDraw#建立一個透明背景的 4K 影像image = Image.new('RGBA', (3840, 2160), (0, 0, 0, 0))#建立一個畫筆draw = ImageDraw.Draw(image)#定義三角形的頂點座標points = [(1920, 800), (1420, 1600), (2420, 1600)]#使用畫筆繪制三角形,填充顏色為藍色,透明度為 255draw.polygon(points, fill=(0, 0, 255, 255))#顯示影像image.show()

3.正方形

from PIL import Image, ImageDraw#建立一個透明背景的 4K 影像image = Image.new('RGBA', (3840, 2160), (0, 0, 0, 0))#建立一個畫筆draw = ImageDraw.Draw(image)#定義正方形外接矩形的左上角和右下角座標left_top = (1620, 960)right_bottom = (2220, 1560)#使用畫筆繪制正方形,填充顏色為綠色,透明度為 255draw.rectangle((left_top, right_bottom), fill=(0, 255, 0, 255))#顯示影像image.show()

4.聖誕樹

from PIL import Image, ImageDraw#建立一個透明背景的 4K 影像image = Image.new('RGBA', (3840, 2160), (0, 0, 0, 0))#建立一個畫筆draw = ImageDraw.Draw(image)#定義樹幹的外接矩形的左上角和右下角座標trunk_left_top = (1820, 1760)trunk_right_bottom = (2020, 1960)#使用畫筆繪制樹幹,填充顏色為棕色,透明度為 255draw.rectangle((trunk_left_top, trunk_right_bottom), fill=(165, 42, 42, 255))#定義樹葉的頂點座標leaves_points = [(1920, 800), (1420, 1600), (1920, 1400), (2420, 1600)]#使用畫筆繪制樹葉,填充顏色為綠色,透明度為 255draw.polygon(leaves_points, fill=(0, 255, 0, 255))#顯示影像image.show()