python 直角圖標生成圓角圖標


參考鏈接:https://stackoverflow.com/questions/11287402/how-to-round-corner-a-logo-without-white-backgroundtransparent-on-it-using-pi

用了三種方法,第三種方法效果最好,效果如下圖:

 

 

需要用到兩個庫:

pip install Pillow
pip install aggdraw

源碼如下:

from PIL import Image,ImageDraw,ImageChops
import aggdraw
import os

def round_corner_jpg(image, radius):
    """generate round corner for image"""
    mask = Image.new('L', image.size) # filled with black by default
    draw = aggdraw.Draw(mask)
    brush = aggdraw.Brush('white')
    width, height = mask.size
    #upper-left corner
    draw.pieslice((0,0,radius*2, radius*2), 90, 180, None, brush)
    #upper-right corner
    draw.pieslice((width - radius*2, 0, width, radius*2), 0, 90, None, brush)
    #bottom-left corner
    draw.pieslice((0, height - radius * 2, radius*2, height),180, 270, None, brush)
    #bottom-right corner
    draw.pieslice((width - radius * 2, height - radius * 2, width, height), 270, 360, None, brush)
    #center rectangle
    draw.rectangle((radius, radius, width - radius, height - radius), brush)
    #four edge rectangle
    draw.rectangle((radius, 0, width - radius, radius), brush)
    draw.rectangle((0, radius, radius, height-radius), brush)
    draw.rectangle((radius, height-radius, width-radius, height), brush)
    draw.rectangle((width-radius, radius, width, height-radius), brush)
    draw.flush()
    image = image.convert('RGBA')
    image.putalpha(mask)
    return image

def get_filePath_fileName_fileExt(fileUrl):
    """
    獲取文件路徑, 文件名, 后綴名
    :param fileUrl:
    :return:
    """
    filepath, tmpfilename = os.path.split(fileUrl)
    shotname, extension = os.path.splitext(tmpfilename)
    return filepath, shotname, extension

if __name__ == '__main__':
    picLocation = 'Sina1.png'
    im = Image.open(picLocation)
    im = round_corner_jpg(im, 20)
    im.save(get_filePath_fileName_fileExt(picLocation)[1]+'_round.png')

順便安利一個免費的開源的看圖片的軟件:https://imageglass.org/ 

 

前面兩種方法效果都不好

第一種方法鋸齒比較明顯

 

第二種方法有白色區域:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM