您好,登錄后才能下訂單哦!
這篇文章給大家介紹使用python怎么實(shí)現(xiàn)一個(gè)九宮格圖片,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
python的數(shù)據(jù)類型:1. 數(shù)字類型,包括int(整型)、long(長整型)和float(浮點(diǎn)型)。2.字符串,分別是str類型和unicode類型。3.布爾型,Python布爾類型也是用于邏輯運(yùn)算,有兩個(gè)值:True(真)和False(假)。4.列表,列表是Python中使用最頻繁的數(shù)據(jù)類型,集合中可以放任何數(shù)據(jù)類型。5. 元組,元組用”()”標(biāo)識,內(nèi)部元素用逗號隔開。6. 字典,字典是一種鍵值對的集合。7. 集合,集合是一個(gè)無序的、不重復(fù)的數(shù)據(jù)組合。
1、原理
用Python制作的九宮格圖像生成器包裝exe文件,用戶無需部署安裝Python的開發(fā)環(huán)境,即可在當(dāng)?shù)剡\(yùn)行該程序,快速生成九宮格圖像。
實(shí)現(xiàn)原理很簡單,就是用PIL庫不斷畫小區(qū)域,切下來存儲成新的小圖片。
2、實(shí)例
假設(shè)每一個(gè)格子的寬和高分別是w、h,那么第row行(從0開始計(jì)數(shù)),第col列(從0開始計(jì)數(shù))的格子左上角坐標(biāo)和右下角坐標(biāo)分別是(col * w, row * h),(col * w + w, r * h + h)。
# -*- coding: UTF-8 -*- # 將一張圖片分成九張,九宮格 import tkinter as tk from PIL import Image import sys #先將 input image 填充為正方形 def fill_image(image): width, height = image.size #選取長和寬中較大值作為新圖片的 new_image_length = width if width > height else height #生成新圖片[白底] new_image = Image.new(image.mode, (new_image_length, new_image_length), color='white') #注意這個(gè)函數(shù)! #將之前的圖粘貼在新圖上,居中 if width > height:#原圖寬大于高,則填充圖片的豎直維度 #(x,y)二元組表示粘貼上圖相對下圖的起始位置,是個(gè)坐標(biāo)點(diǎn)。 new_image.paste(image, (0, int((new_image_length - height) / 2))) else: new_image.paste(image, (int((new_image_length - width) / 2),0)) return new_image # 分割圖片 def cut_image(image): width, height = image.size item_width = int(width / 3) #因?yàn)榕笥讶σ恍蟹?張圖。 box_list = [] # (left, upper, right, lower) for i in range(0,3): for j in range(0,3): #print((i*item_width,j*item_width,(i+1)*item_width,(j+1)*item_width)) box = (j*item_width,i*item_width,(j+1)*item_width,(i+1)*item_width) box_list.append(box) image_list = [image.crop(box) for box in box_list] return image_list #保存圖片 def save_images(image_list): index = 1 for image in image_list: image.save(str(index) + '.png', 'PNG') index += 1 # 點(diǎn)擊按鈕,實(shí)現(xiàn)圖片分割 def cTofClicked(): file_path=str(entryCd.get()) # 獲取要進(jìn)行分割的圖片路徑 image = Image.open(file_path) #image.show() image = fill_image(image) image_list = cut_image(image) save_images(image_list) labelcTof.config(text="九宮格圖片已生,請?jiān)诔绦蛩谀夸洸榭矗?quot;) # 窗體 top=tk.Tk() top.title('九宮格圖片生成器') labelcTof=tk.Label(top,text="請輸入要進(jìn)行轉(zhuǎn)換的圖片路徑:",height=4,\ width=40,fg="blue") labelcTof.pack() entryCd=tk.Entry(top,text='0') # 文本框,獲取圖片路徑 entryCd.pack() label_tip=tk.Label(top,text="請檢查圖片路徑是否輸入正確!",height=2,\ width=40,fg="gray") label_tip.pack() btnCal=tk.Button(top,text="點(diǎn)擊生成九宮格圖片",fg="red",bg="yellow",command=cTofClicked) # 點(diǎn)擊回調(diào)函數(shù) btnCal.pack() top.mainloop() # 執(zhí)行主循環(huán)
關(guān)于使用python怎么實(shí)現(xiàn)一個(gè)九宮格圖片就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。