python實現圖片九宮格分割的示例
大家都知道在微信朋友圈或者微博以及QQ動態中,有很多“強迫癥患者”發圖片都愛發9張,而有些圖是一張圖片分成的九宮圖,對于這種操作,大家知道是怎么做到的嗎?
本文就是用Python做的一個九宮格圖片生成器,是一個打包好的exe文件,用戶無需部署安裝Python的開發環境,在本地就可以運行此程序,以此快速生成九宮格圖片。
實現原理實現原理非常簡單,那就是利用PIL庫對原圖不斷畫小區域然后切下來存儲成新的小圖片。
假設每一個格子的寬和高分別是w、h,那么第row行(從0開始計數),第col列(從0開始計數)的格子左上角坐標和右下角坐標分別是(col * w, row * h),(col * w + w, r * h + h)。
下面是程序的所有代碼,這是一個Python GUI程序,代碼不多,也很容易理解:
# -*- coding: UTF-8 -*-# 將一張圖片分成九張,九宮格import tkinter as tkfrom 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’) #注意這個函數! #將之前的圖粘貼在新圖上,居中 if width > height:#原圖寬大于高,則填充圖片的豎直維度 #(x,y)二元組表示粘貼上圖相對下圖的起始位置,是個坐標點。 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) #因為朋友圈一行放3張圖。 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 # 點擊按鈕,實現圖片分割def cTofClicked(): file_path=str(entryCd.get()) # 獲取要進行分割的圖片路徑 image = Image.open(file_path) #image.show() image = fill_image(image) image_list = cut_image(image) save_images(image_list) labelcTof.config(text='九宮格圖片已生,請在程序所在目錄查看!') # 窗體top=tk.Tk()top.title(’九宮格圖片生成器’)labelcTof=tk.Label(top,text='請輸入要進行轉換的圖片路徑:',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='點擊生成九宮格圖片',fg='red',bg='yellow',command=cTofClicked) # 點擊回調函數btnCal.pack() top.mainloop() # 執行主循環運行結果
界面圖像
在文本框中輸入圖片地址,點擊“點擊生成九宮格圖片”
以上就是python實現圖片九宮格分割的示例的詳細內容,更多關于python 圖片九宮格分割的資料請關注好吧啦網其它相關文章!
相關文章:
1. CentOS郵件服務器搭建系列—— POP / IMAP 服務器的構建( Dovecot )2. 在JSP中使用formatNumber控制要顯示的小數位數方法3. django創建css文件夾的具體方法4. jsp網頁實現貪吃蛇小游戲5. ASP中if語句、select 、while循環的使用方法6. .NET SkiaSharp 生成二維碼驗證碼及指定區域截取方法實現7. MyBatis JdbcType 與Oracle、MySql數據類型對應關系說明8. ASP中實現字符部位類似.NET里String對象的PadLeft和PadRight函數9. 存儲于xml中需要的HTML轉義代碼10. 利用CSS制作3D動畫
