不到20行實(shí)現(xiàn)Python代碼即可制作精美證件照
無論是我們上學(xué)時(shí)還之后的工作中,基本都需要用到電子證件照片,這類照片基本都對(duì)照片尺寸、背景色有要求,本文我們來看一下如何只用不到 20 行 Python 代碼完成證件照片的制作。
簡介
制作證件照我們主要有兩個(gè)工作:修改照片背景和修改照片尺寸,修改背景我們需要用到第三方庫 removebg,修改照片尺寸需要用到 PIL 庫,這兩個(gè)庫的安裝使用 pip install removebg 和 pip install Pillow 即可。
使用 removebg 時(shí),我們還需要一個(gè) API 密鑰,獲取方式為:首先,我們打開鏈接地址 https://accounts.kaleido.ai/users/sign_up 注冊(cè)一個(gè)賬戶,打開后如下圖所示:
我們填寫郵箱和密碼再勾選同意協(xié)議后提交,之后該網(wǎng)站會(huì)給我們剛剛填寫的郵箱發(fā)送一條驗(yàn)證信息,我們進(jìn)到自己的郵箱點(diǎn)擊驗(yàn)證鏈接完成驗(yàn)證之后即完成了賬號(hào)的注冊(cè)工作。
賬號(hào)注冊(cè)好之后,我們接著打開 https://www.remove.bg/zh/profile#api-key 地址登錄自己的賬號(hào),即可進(jìn)入到下圖位置:
我們點(diǎn)擊上圖中的顯示按鈕,就可以拿到秘鑰了。
代碼實(shí)現(xiàn)
代碼實(shí)現(xiàn)也比較簡單,還是我們之前說的思路:使用 removebg 庫修改照片背景色,使用 PIL 庫修改照片尺寸,具體實(shí)現(xiàn)如下所示:
from PIL import Imagefrom removebg import RemoveBg# 修改照片背景色def change_bgcolor(file_in, file_out, api_key, color): rmbg = RemoveBg(api_key, ’error.log’) rmbg.remove_background_from_img_file(file_in) no_bg_image = Image.open(file_in) x, y = no_bg_image.size new_image = Image.new(’RGBA’, no_bg_image.size, color=color) new_image.paste(no_bg_image, (0, 0, x, y), no_bg_image) new_image.save(file_out)# 修改照片尺寸def change_size(file_in, file_out, width, height): image = Image.open(file_in) resized_image = image.resize((width, height), Image.ANTIALIAS) resized_image.save(file_out)
我們可以看出整個(gè)實(shí)現(xiàn)過程只用了不到 20 行代碼。
效果展示
最后我們來看一下實(shí)現(xiàn)效果:
到此這篇關(guān)于不到20行實(shí)現(xiàn)Python代碼即可制作精美證件照的文章就介紹到這了,更多相關(guān)Python 證件照內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 解決Android Studio 格式化 Format代碼快捷鍵問題2. php解決注冊(cè)并發(fā)問題并提高QPS3. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問題4. 在Chrome DevTools中調(diào)試JavaScript的實(shí)現(xiàn)5. Springboot 全局日期格式化處理的實(shí)現(xiàn)6. Java使用Tesseract-Ocr識(shí)別數(shù)字7. SpringBoot+TestNG單元測試的實(shí)現(xiàn)8. vue實(shí)現(xiàn)web在線聊天功能9. JS原生2048小游戲源碼分享(全網(wǎng)最新)10. Python使用urlretrieve實(shí)現(xiàn)直接遠(yuǎn)程下載圖片的示例代碼
