喜歡Bing壁紙,考慮把它設置到自己一個插件的背景,但想從一個固定的地址獲取圖片。
就打算用寫一個腳本定時獲取Bing首頁圖片,寫到自己網站目錄下的固定地址。
后來發現圖片用作背景時加上虛化有時候會好一點,就又添加了虛化部分。
以下為記錄。
代碼用到的第三方模塊為
Pillow-5.1.0
+requests-2.18.4
,在Python 2.7 + CentOS 7.2
與Python 3.6 + Win10
環境下均正確工作。
流程:
- 寫腳本獲取Bing首頁圖片并保存到本地
- 獲取Bing首頁圖片網址
- 下載圖片,保存原圖
- 處理圖片,做高斯模糊后保存虛化版本
- 服務器定時執行腳本
-
crontab
定時任務
-
正文
腳本部分
import requests
import re
from PIL import Image, ImageFilter
def fetch_today_image_url():
"""
獲取每日圖片的地址
"""
response = requests.get(
"https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1").text # 請求官方接口
# 匹配出/az......jpg,既圖片網址
partial_url = re.match(r'.*(/az.*\.jpg)', response).group(1)
return "https://cn.bing.com" + partial_url
def download_image(url, path):
"""
通過requests庫將圖片下載到本地
"""
ir = requests.get(url)
if (ir.status_code == 200):
open(path, "wb").write(ir.content)
def create_blur_image(path, redius=20):
"""
將圖片進行高斯模糊后修改后綴另行保存
"""
origin = Image.open(path)
treated = origin.filter(ImageFilter.GaussianBlur(redius))
img_path_blur = path.replace(".jpg", "_blur.jpg")
treated.save(img_path_blur)
if (__name__ == "__main__"):
img_url = fetch_today_image_url()
img_path = r"C:/users/kwokg/Desktop/bing.jpg" # 設置圖片保存路徑
download_image(img_url, img_path)
create_blur_image(img_path)
服務器執行部分
使用crontab -e
編輯定時任務配置文件,在末尾添加下邊的內容(每小時執行一次指定路徑下的腳本):
* */1 * * * python /opt/script/bing_today.py &
另外,一些命令
- pip使用清華源,(
~/.pip/pip.conf
文件,沒有自己創建即可)[global] index-url = https://pypi.tuna.tsinghua.edu.cn/simple [install] trusted-host=pypi.tuna.tsinghua.edu.cn