2026年11月10日火曜日

画像の角を丸くするpython3スクリプトで、色褪せて、加工されますが、何か、いい方法は?、

from PIL import Image, ImageDraw

img = Image.open("texedicon.png").convert("RGBA")

w, h = img.size
r = int(min(w, h) * 0.15)

mask = Image.new("L", (w, h), 0)
draw = ImageDraw.Draw(mask)
draw.rounded_rectangle((0,0,w,h), radius=r, fill=255)

img.putalpha(mask)
img.save("01-rounded.png")
ーーーーー     色褪せて、加工されますが、何か、いい方法は?、

はい、あります。

実は、このコード自体は色を変更していません。

img.putalpha(mask)
 

はアルファチャンネル(透明度)を付けるだけです。

ですので、色褪せて見える原因は PNG を表示しているソフト側であることが多いです。

方法1 一番きれい(おすすめ)

ImageOps.fit() と rounded_rectangle() を使ってマスクだけ作ります。

 
from PIL import Image, ImageDraw

img = Image.open("texedicon.png").convert("RGBA")

w, h = img.size
radius = int(min(w, h) * 0.15)

mask = Image.new("L", (w, h), 0)
draw = ImageDraw.Draw(mask)
draw.rounded_rectangle((0, 0, w, h), radius=radius, fill=255)

result = Image.new("RGBA", (w, h), (0, 0, 0, 0))
result.paste(img, (0, 0), mask)

result.save("rounded.png")
 

こちらの方が元画像の色を維持しやすいです。


方法2 アンチエイリアスを掛ける

ギザギザ防止のために4倍で作って縮小します。

 
from PIL import Image, ImageDraw

img = Image.open("texedicon.png").convert("RGBA")

scale = 4

w, h = img.size
radius = int(min(w, h) * 0.15 * scale)

mask = Image.new("L", (w*scale, h*scale), 0)

draw = ImageDraw.Draw(mask)
draw.rounded_rectangle(
    (0, 0, w*scale, h*scale),
    radius=radius,
    fill=255
)

mask = mask.resize((w, h), Image.LANCZOS)

img.putalpha(mask)
img.save("rounded.png")
 

かなり自然になります。


方法3 アイコンなら一番おすすめ

アイコンなら

ImageMagick

の

magick texedicon.png \
-alpha set \
\( +clone -alpha extract -draw "roundrectangle 0,0,511,511,70,70" \) \
-compose CopyOpacity -composite rounded.png
 

の方が品質が高いです。


気になること

「色褪せる」というのは

  • ① 全体が白っぽくなる
  • ② 半透明になる
  • ③ 黒っぽくなる
  • ④ 色が薄くなる

のどれでしょうか?

また、texedicon.png をアップロードしていただければ、色を変えずに角丸にする方法を確認して、最適なコードをご提案できます。

0 件のコメント: