1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
# 合并成多行文字图片
def combine_image_with_multi(paths, merge_times, is_debug = False):
count = len(paths)
src_image = Image.open(paths[0])
image_width, image_height = src_image.size
x = image_width + extra_bound_as_multi_line
y = image_height + extra_bound_as_multi_line
# 根据待合并的图片总数来计算平铺的行列数
sqrt2 = math.sqrt(count)
row_num = round(sqrt2)
column_num = row_num
if sqrt2 > column_num:
column_num = column_num + 1
print("总数:%d 开根号:%f 行:%d 列:%d" % (count, sqrt2, row_num, column_num))
# 计算合并之后的图片尺寸
full_x = x * column_num
full_y = y * row_num
full_size = (full_x, full_y)
full_image = Image.new('RGBA', full_size, (255,255,255))
print("full rect : {%d,%d,%d,%d}" % (0, 0, full_x, full_y))
# 将图片块平铺到这个大图片上
start_x = 0
start_y = 0
end_x = x
end_y = y
index = 1
draw = ImageDraw.Draw(full_image)
for path in paths:
if is_debug == True:
# 绘制每个填充区域的边界
print("{%d,%d,%d,%d}" % (start_x, start_y, end_x, end_y))
draw.rectangle((start_x+1, start_y+1, end_x-1, end_y-1), outline = get_random_color())
# 居中绘制填充的图片索引
index_str = "%d"%(index)
font_size_x, font_size_y = draw.textsize(index_str)
draw.text((start_x + (x-font_size_x)/2, start_y + (y-font_size_y)/2), index_str, fill='black')
else:
src_image = Image.open(path)
start_x0 = start_x + (x-image_width)//2
start_y0 = start_y + (y-image_height)//2
end_x0 = start_x0 + image_width
end_y0 = start_y0 + image_height
full_image.paste(src_image, (start_x0, start_y0, end_x0, end_y0), src_image)
index = index + 1
if end_x >= full_x:
# 从左往右填充,遇到边界之后切换到下一行
start_x = 0
end_x = start_x + x
start_y = start_y + y
end_y = start_y + y
else:
# 继续从左往右平铺
start_x = start_x + x
end_x = end_x + x
current_dir = os.getcwd()
output_path = '%s/../multi_line_%d.png' % (current_dir, merge_times)
full_image.save(output_path)
|