回答編集履歴

1

サンプル追加

2018/05/21 08:55

投稿

can110
can110

スコア38266

test CHANGED
@@ -45,3 +45,59 @@
45
45
  実行結果
46
46
 
47
47
  ![イメージ説明](119d870cea0b64fff4554a23074e3492.png)
48
+
49
+
50
+
51
+
52
+
53
+ `Python`コードで透過する文字画像を作成し、重ねて描画するサンプルを書いてみました。
54
+
55
+ ```Python
56
+
57
+ from PIL import Image, ImageDraw, ImageFont
58
+
59
+
60
+
61
+ # 透過する文字画像を作成
62
+
63
+ img = Image.new('RGBA', (640,480),(0,0,0,0)) # 適当なサイズの透過画像を生成
64
+
65
+ draw = ImageDraw.Draw(img)
66
+
67
+ font = ImageFont.truetype("arial.ttf", 24) # 適当な大きさのフォントで
68
+
69
+ x,y,max_w = 0,90,0 # 適当な位置から
70
+
71
+ DOCS = ['I am a dog.','As yet I have no name.',"I've no idea where I was born."]
72
+
73
+ for text in DOCS:
74
+
75
+ draw.text((x,y), text, fill=(0,0,0), font=font)
76
+
77
+ w,h = font.getsize(text)
78
+
79
+ max_w = max(max_w, w)
80
+
81
+ y += h
82
+
83
+ img = img.crop((0, 0, max_w, y)) # 画像サイズをテキスト範囲に合わせて調整
84
+
85
+ img.save('name.png')
86
+
87
+
88
+
89
+ # 犬の画像にテキスト画像を重ねる
90
+
91
+ card = Image.open("img.png").convert("RGBA") # 犬
92
+
93
+ #img = Image.open("name.png").convert("RGBA") # 文字
94
+
95
+ x, y = img.size
96
+
97
+ card.paste(img, (0, 0), img)
98
+
99
+ card.save("test.png")
100
+
101
+ ```
102
+
103
+ ![イメージ説明](34ba1e2a0bc3375cb8036422cb8a3d31.png)