最近在公司做項目,與地圖有關的一個東西,程序中使用的地圖是一副很大的圖片,為了速度和內存的考慮,我們把圖片切分成塊,然後根據坐標解決顯示某一塊,以此來提高程序速度,為了得到這些小塊圖片,寫了一個小腳本來處理這個問題,現學現賣,看代碼:
#切分圖片腳本

import Image,os

def SplitImage(filepath,savepath):

img = Image.open(filepath)

ImageSize = img.size

Width = ImageSize[0]

Height = ImageSize[1]

for w in range(0,Width/800+1):

for h in range(0,Height/600+1):

left = 800*w

top = 600*h

right = left+800

if right >Width:

right = Width

bottom = top + 600

if bottom >Height:

bottom = Height

if right - left > 0 and bottom - top > 0:

box = (left,top,right,bottom)

sub = img.crop(box)

path = savepath + '\' +str(w) +'_' + str(h)+'.jpg'

sub.save(path)
Python是一門比較強大的腳本語言,在每個方面它都有比較深入的應用,使用第三方庫PIL,我們能夠實現一些很實用的代碼,下面這個則是為圖片添加簡單水印的代碼,對於批量處理圖片的用戶很實用

import Image, ImageDraw, ImageFont

import math


img = Image.open("123.gif")

img.convert("RGB")

font = ImageFont.truetype(('C:\Windows\Fonts\arial.ttf'),25)


imgWidth = img.size[0]

imgHeight = img.size[1]

watermark = Image.new("RGBA", (imgWidth*2, imgHeight*2))

draw = ImageDraw.Draw(watermark, "RGBA")


draw.setfont(font)

for i in range(0,imgWidth*2,150):

for j in range(0,imgHeight*2,30):

draw.text((i,j),"breakind")


watermark = watermark.rotate(46)

topaste = watermark.crop((imgWidth/2,imgHeight/2,imgWidth*3/2,imgHeight*3/2))

mask = topaste.convert("L").point(lambda x: min(x, 50))

topaste.putalpha(mask)

img.paste(topaste, None, topaste)

img.save("out.gif")
效果:
Python真的是蠻強大的,作為閒時無聊的調劑不錯,也可以寫出很多實用的代碼來用,推薦