代码拉取完成,页面将自动刷新
import os,math
import time
from PIL import Image
# http://www.cnblogs.com/ecofast/p/5487926.html
# https://python-pillow.org
def splitimage(src, dstpath):
img = Image.open(src)
w, h = img.size
smallSize = 256
rownum = math.ceil(h/smallSize)
colnum = math.ceil(w/smallSize)
if rownum <= h and colnum <= w:
print('Original image info: %sx%s, %s, %s' % (w, h, img.format, img.mode))
print('开始处理图片切割, 请稍候...')
s = os.path.split(src)
if dstpath == '':
dstpath = s[0]
fn = s[1].split('.')
basename = fn[0]
ext = fn[-1]
num = 0
rowheight = h // rownum #取整除 - 返回商的整数部分
colwidth = w // colnum
for r in range(rownum):
for c in range(colnum):
box = (c * colwidth, r * rowheight, (c + 1) * colwidth, (r + 1) * rowheight)
img.crop(box).save(os.path.join(dstpath, basename + '_' + str(num) + '.' + ext), 'jpeg')
num = num + 1
print('图片切割完毕,共生成 %s 张小图片。' % num)
else:
print('不合法的行列切割参数!')
def get_dir_imgs(dirUrl):
files = os.listdir(dirUrl)
result = [ os.path.join(dirUrl,f) for f in files if os.path.isfile(os.path.join(dirUrl,f))]
return result
def split_img(src,saveUrl):
img = Image.open(src)
w, h = img.size
smallSize = 256
rownum = math.ceil(h/smallSize)
colnum = math.ceil(w/smallSize)
for col in range(0,colnum):
for row in range(0,rownum):
left = col*smallSize
uper = row*smallSize
box = (left,uper,left+smallSize,uper+smallSize) #左上右下
a = ""
b = ""
c = ""
tarUrl = os.path.join(saveUrl,str(col)+"_"+str(row)+".jpg")
img.crop(box).save(tarUrl)
print("saveUrl:",tarUrl)
src = "D:/srcimg/big.jpg"
#src = "D:/srcimg/scene.jpg"
saveUrl = "D:\imgsave"
'''
imgs = "D:/srcimg"
fs = get_dir_imgs(imgs)
src = fs[0]
print(fs)
'''
#splitimage(src, '')
st = time.time()
split_img(src,saveUrl)
et = time.time()
print('cost time :',et-st)
'''
src = input('请输入图片文件路径:')
if os.path.isfile(src):
dstpath = input('请输入图片输出目录(不输入路径则表示使用源图片所在目录):')
if (dstpath == '') or os.path.exists(dstpath):
row = int(input('请输入切割行数:'))
col = int(input('请输入切割列数:'))
if row > 0 and col > 0:
splitimage(src, row, col, dstpath)
else:
print('无效的行列切割参数!')
else:
print('图片输出目录 %s 不存在!' % dstpath)
else:
print('图片文件 %s 不存在!' % src)
'''
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。