本例是用Python Image Library(PIL)的Image模块进行图片处理,并把保存的图片设置成桌面。在此之前,当然还是要用urllib取得网站的response。
PIL 是Python下最有名的影像处理套件,由许多不同的模块所组成,并且提供了许多的处理功能,允许我们在简单的Python程序里进行影像的处理。 使用像 PIL 这样的程序库套件可以帮助我们把精力集中在影像处理的工作本身,避免迷失在底层的算法里面。由于影像处理牵涉到了大量的数学运算,因此PIL中有許多的模块是用 C 语言所写成的,以提升处理的效率。
当我们使用微软的
Bing的时候,会发现每天背景图片都是不一样的,但每张都很漂亮。鉴于最近在学习python,就萌生了获取每日Bing图片的想法,代码取自网上,我只是做了分析。
工作步骤:
-
取得
Bing的response,分析一下
Bing主页的源代码,有var g_img={url:'\/fd\/hpk2\/ShuBrocade_ZH-CN760216482.jpg',id:'bgDiv',d:200,cN:'_SS',crN:'bIm',hash:'648'};sc_bgL(),在这里就是需要取得背景图片的地方。因为整个源代码只有这一处,所以可以用index('
'g_img={url:')的方法去过滤背景图片的地址:content = urllib.urlopen('http://cn.bing.com/').read()
tempStr = content[content.index('g_img={url:')+12 : len(content)]
tempStr = tempStr[0 : tempStr.index(',id:')-1]
tempStr = tempStr.replace('\\', '')
bgImageUrl = 'http://cn.bing.com'+tempStr
- 下载图片的时候,使用urlretrieve(url, filename=None, reporthook=None, data =None)
- 使用win32gui.SystemParametersInfo(Action, Param, WinIni)
Code
#!/usr/bin/env python
#coding=utf-8
import os
import sys
import random
import urllib
import win32gui
import win32con
import Image
class Bing:
def __init__(self):
self.content = urllib.urlopen("http://cn.bing.com/").read()
self.bgImageUrl = ''
self.localFileName = ''
self.localBMPFileName = ''
def parseImageURL(self):
tempStr = self.content[self.content.index('g_img={url:')+12 : len(self.content)]
tempStr = tempStr[0 : tempStr.index(',id:')-1]
tempStr = tempStr.replace('\\', '')
self.bgImageUrl = 'http://cn.bing.com' + tempStr
#only use for generate file name in local
def createLocalFileName(self):
randomStr = ''.join(random.sample(['a','b','c','d','e','f','g','h','i','j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'], 6)).replace(" ", "")
self.localFileName = "D:/Bing/" + randomStr + ".jpg"
self.localBMPFileName = "D:/Bing/" + randomStr + ".bmp"
def downloadImage(self):
if self.bgImageUrl == "":
self.parseImageURL()
if self.localFileName == "":
self.createLocalFileName()
data = urllib.urlretrieve(self.bgImageUrl, self.localFileName)
def updateBGImage(self):
img = Image.open(self.localFileName)
img.save(self.localBMPFileName)
os.remove(self.localFileName)
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, self.localBMPFileName, 0)
if __name__ == '__main__'== "__main__":
bing = Bing()
bing.downloadImage()
bing.updateBGImage()