废话

朋友问我能不能搞个九图切割的小软件,我就着手搞了
不过这次注释我会用英文写

九图切割

一、需求

  • 选择图片路径
  • 裁剪图片成九张
  • 保存裁剪的九张图片

二、步骤分析

  1. 选择图片
  2. 打开图片
  3. 裁剪图片
  4. 保存裁剪的九张图片
    这里做的途中发现一个小问题,于是中途加了一个步骤,等等说

三、代码框架

我发现写框架是个很好的方式,看的时候不会纠结于具体的语言细节,而是先理清楚程序的功能逻辑

# import modules
from someModule import someMethod# some functions
def get_pic():# get the image from the path givenpassdef cut_pic():# cut the picture into 9 picecs# the main function of this programpassdef save_pic():# choose path and save the cutted picturepass# use class to build GUI
# I was mentioned in my last blog
class Main_Function():def __init__(self,master):# build the body of my GUImastera Entry() that show the patha Button() used to choose patha Button() used to begin cut and automatical savepassdef Choose(self):# bind to the first button# choose pic's pathpassdef Cut(self):# bind to the second button# begin cut and save automaticallypass# some basic program
def main():root = Tk()app = Main_Function(root)root.mainloop()if __name__ == "__main__":main()

四、具体填充代码

这是一句鼓励的话:实际学习的时候并不会想看代码一样流程非常轻松地就出来了,我也是从懵逼到查资料到写出代码。
我自己在记录这个流程的时候是尽量保证逻辑连贯性的,所以看上去非常得easy,不过如果自己写代码特备hard的话,不要灰心丧气哈~

import modules部分

GUI采用tkinter,图片处理用PIL

from tkinter import *
from tkinter import filedialog # this is used to choose path
from PIL import Image

get_pic 函数

实现很简单,其实可以直接写在其他函数里,但是写在外面对于整体结构的表达看起来更清楚

def get_pic(pic_path):return Image.open(pic_path)

cut_pic函数

def cut_pic(img):# use list r_image to save all the pictures cuttedr_image = []# img.size stores the size of the picture# [0] is x axis, [1] is y axisx = img.size[0]y = img.size[1]# cut to 9 piecesfor i in range(3):for j in range(3):# use crop to cutr_image.append(img.crop((j*x/3,i*y/3,(j+1)*x/3,(i+1)*y/3)))# this sentence to confirm that my prgram works correctlyprint("%d th pic cut success" %(i+j*3))return r_image

save_pic函数

def save_pic(img):# store 9 pictures in orderfor i in range(9):img[i] = img[i].resize((128,128))# name the picturename = "cut_pic_"+str(i)+".png"# use save to saveimg[i].save(name)# this sectence is used to confirm that my program works correctlyprint("%d th pic save success" % i)

Main_Function

class Main_Function():def __init__(self,master):# build the masterself.master = master# set the titlemaster.title("PNG Picture Cutter")# set the GUI's position# get the height and width of the screenws = master.winfo_screenwidth()hs = master.winfo_screenheight()# calculate the position of x & yx = (ws/2)-300y = (hs/2)-200master.geometry('500x50+%d+%d' % (x,y))# can't change the size of the tk()master.resizable(False,False)# the Entry shows the path of the pictureself.content = Entry(master,width=40)# use pack to place the Entryself.content.pack(side=LEFT)# the Button to start cutself.CutPic= Button(master,text="Cut",command=self.Cut)self.CutPic.pack(side=RIGHT)# the Button to choose picture's pathself.ChoosePic = Button(master,text="Choose pic",command=self.Choose)self.ChoosePic.pack(side=RIGHT)# pack CutPic and ChoosePic in this order to make sure the second button appears in the left.def Choose(self):# bind the function to button 1# you can test 'askopenfilename()' in other programe, it's very useful, you will love it.self.FilePath = filedialog.askopenfilename()# clear the content of the Entry(), make it able for insertself.content.delete(0,'end')# write the path in the Entry()self.content.insert(0,self.FilePath)def Cut(self):# use get() to get the content of the Entry()path=self.content.get()# get the pictureimg = get_pic(path)# cut the picturer_img = cut_pic(img)# save picturessave_pic(r_img)

五、功能修正

1.界面布局修正

当时只是纯粹放下了三个控件,想让文本框在左边,choose在中间,cut在右边。简单写了.pack(side=LEFT)这种形式的代码
呈现效果就这么丑……

然后思考了一下该怎么改
可以用一个Frame控件,让Frame控件置中,其他的三个控件在Frame中布局。
这样的pace(side=xxxx)就不会让控件变到最边缘了

这是布局的修改代码:

     # use frame to control the positionself.frame = Frame(master)self.frame.pack()# attention!!            ↓↓↓self.content = Entry(self.frame,width=40)self.content.pack(side=LEFT)# attention!!               ↓↓↓self.Translate = Button(self.frame,text="Cut",command=self.Cut)self.Translate.pack(side=RIGHT)# attention!!             ↓↓↓self.ChoosePDF = Button(self.frame,text="Choose pic",command=self.Choose)self.ChoosePDF.pack(side=RIGHT)

代码修改后的呈现效果是这样的,美观了很多(自卖自夸)

实际上可以用grid和place直接来布局,但是我还没用到,pack在这里很迅速很简洁

2.空白填补

直接切九图,图片如果原本不是正方形,切出的图片都会是长方形,在朋友圈发图的时候上下边缘会被隐藏。
后来查资料,用resize拉伸图形到统一尺寸。详情见函数save_pic()
试验后发现这种拉伸非常暴力,原本的图片比例会被破坏。
于是想要一种在空白处填补白色的算法,查阅资料后发现了如下代码,构造了fill_image()

def fill_image(image):# size[0] is the width, size[1] is the heightwidth,height = image.size# new_length records the maxmiun between width and heightnew_length = width if width > height else height# The Magic Code :)# create a white imager_image = Image.new(image.mode,(new_length,new_length),color='white')# paste the original image to the white backgroundif width>height:r_image.paste(image,(0,int((new_length-height)/2)))else:r_image.paste(image,(int((new_length-width)/2),0))return r_image

然后在整体代码中添加使用这个函数。
一个位置是可以在button调用cut函数的时候先fill
还有一个位置是可以在外部的函数cut_pic()里先fill
我选择前者,于是修改后的代码如下:

    def Cut(self):path=self.content.get()# get the pictureimg = get_pic(path)# turn to squareimg = fill_image(img)# cut the picturer_img = cut_pic(img)# save picturessave_pic(r_img)

六、参考资料

学到了加白边框的方法https://blog.csdn.net/eereere/article/details/79604682
其余资料后期再补,因为搜索地有点杂

七、后记


救命! 她使用了可爱攻击

python学习笔记 -- 03 实现切割九图相关推荐

  1. 【Python教程】雨痕 的《Python学习笔记》(附脑图)

    本文转自至:http://www.pythoner.com/148.html 近日,在某微博上看到有人推荐了这本作者是 雨痕 的<Python学习笔记>,从github上下载下来看了下,确 ...

  2. python笔记图片_【Python教程】雨痕 的《Python学习笔记》(附脑图)

    更多 近日,在某微博上看到有人推荐了这本作者是 雨痕 的<Python学习笔记>,从github上下载下来看了下,确实很不错. 注意,这本学习笔记不适合Python新手学习. 从目录上看, ...

  3. Python学习笔记-03

    第三章 基本数据类型 学习要点 数字类型:整数类型.浮点数类型和复数类型 数字类型的运算:数值运算操作.数值运算函数 字符串类型及格式化:索引.切片.基本的format()格式化方法 字符串类型的操作 ...

  4. 学习笔记(03):四十九课时精通matlab数学建模-精通matlab单元数组和结构体深入学习...

    立即学习:https://edu.csdn.net/course/play/25039/288866?utm_source=blogtoedu 1.单元数组的建立 c={'大仙','daxian':[ ...

  5. python学习笔记(二十九)网络通信之模仿qq的在线聊天工具

    基于之前学习过的进程与线程的知识以及网络通信tcp与udp的原理,可以编写一个模仿qq的小程序 一.操作界面:(比较简陋,可以根据自己的要求来更改样式) 1.服务器界面: 2.客户端界面 3.首先启动 ...

  6. 流畅python学习笔记:第十九章:动态属性和特性

    首先来看一个json文件的读取.书中给出了一个json样例.该json文件有700多K,数据量充足,适合本章的例子.文件的具体内容可以在http://www.oreilly.com/pub/sc/os ...

  7. python学习笔记02

    python学习笔记02 面向对象Object Oriented 概述 类和对象 封装 继承 多态 类与类的关系 设计原则 总结 python学习笔记03 面向对象Object Oriented 概述 ...

  8. python语言描述思维导图_雨痕 的《Python学习笔记》--附脑图(转)

    近日,在某微博上看到有人推荐了 雨痕 的<Python学习笔记>,从github上下载下来看了下,确实很不错. 注意,这本学习笔记不适合Python新手学习. 从目录上看,并不能看出这本笔 ...

  9. MySQL学习笔记03【数据库表的CRUD操作、数据库表中记录的基本操作、客户端图形化界面工具SQLyog】

    MySQL 文档-黑马程序员(腾讯微云):https://share.weiyun.com/RaCdIwas 1-MySQL基础.pdf.2-MySQL约束与设计.pdf.3-MySQL多表查询与事务 ...

最新文章

  1. go语言中fmt包中Print、Printf、Println输出相关函数的区别
  2. linux中vim常用命令总结
  3. 【整理】ABAP快捷启动Debug三种方式
  4. AJAX——与服务器交换数据并更新部分网页技术
  5. MFC中的模态对话框与非模态对话框
  6. 计算机发展史的十大成就,2019中国十大科技成就:数个“第一”创造历史
  7. WinForm控件之【LinkLabel】
  8. 计算机主机温度,计算机的理想工作温度和湿度分别是多少
  9. mdb文件取消隐藏_webshellphp隐藏技巧
  10. mybatis逆向工程用idea通过pom插件generator生成代码指令(mysql,oracle,sqlserver)
  11. 微服务学习之Gateway服务网关【Hoxton.SR1版】
  12. 论文笔记_SLAM_Visual SLAM and Structure from Motion in Dynamic Environments A Survey
  13. 嵩天python笔记_嵩天Python学习笔记
  14. PS调色技巧及HSB调色原理
  15. 计算机替换字体怎么操作,字体管家怎么换字体 电脑更换字体的教程介绍
  16. redis中以目录形式存储和读取数据
  17. 超级哄女孩工具之一千枝会动的玫瑰实现
  18. 微信小程序3-模板与配置
  19. 安卓手机屏幕投射电脑 手机投屏到win7
  20. java如何excel导入_java实现Excel导入(迭代一)

热门文章

  1. 使用FRP内网穿透实现外网访问局域网并远程连接
  2. VO、DTO、DO、PO 概念及其区别
  3. 多测师肖sir_高级金牌讲师_第2个月第16讲性能测试之nmon(006)
  4. 德国电信先于竞争对手宣布将在德国推5G网络 明年覆盖20城
  5. ORA-39126: Worker unexpected fatal error in KUPW$WORKER.FIXUP_MASTER_TABLE_EXPORT
  6. ElasticSearch学习_陶文2_时间序列数据库的秘密(2)——索引
  7. Python语言学习:Python语言学习之正则表达式常用函数之re.search方法【输出仅一个匹配结果(内容+位置)】、re.findall方法【输出所有匹配结果(内容)】案例集合之详细攻略
  8. SQL Server 2008 的版本和组件
  9. Linux which命令的使用方法
  10. Beautifulsoup4库提取数据详解