【教学类-09-06】20240401细线迷宫图01+箭头图片(A4横版一页-1份横版)

本文介绍了如何使用Python和相关库如matplotlib生成细线条迷宫图,并将其添加箭头后合并到Word文档和PDF中,适用于教学和分享。作者提供了详细的代码示例和步骤,包括图片生成、箭头插入以及最终的PDF整合过程。
摘要由CSDN通过智能技术生成

作品展示

fbcd67de55964391b0e5b186cd6badbc.png

背景需求:

前期基础上继续优化迷宫图

【教学类-09-05】20240402细线迷宫图03+箭头图片(A4横版一页-4份横版)-CSDN博客文章浏览阅读239次,点赞11次,收藏4次。【教学类-09-05】20240402细线迷宫图03+箭头图片(A4横版一页-4份横版)https://blog.csdn.net/reasonsummer/article/details/137207379?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22137207379%22%2C%22source%22%3A%22reasonsummer%22%7D

素材准备

59020178022e44168f619c2d19c3fd5d.png

09b498d04d7c41a09b1368f58cf069d3.png

word模板

c762b50da1fb437c9ec1595e9713c1f2.png

3f7353d3894e4c1dbf5bc0f7af7d825f.png

重点说明

f23855bf6fc84a96b9190a70de325eaa.png

代码展示

'''
批量制作细线条的迷宫图(A4横板一面一份横版)+图片加箭头图片
作者:
1、落难Coder https://blog.csdn.net/u014297502/article/details/124839912
2、AI对话大师、
3、阿夏
作者:2024年4月3日
'''


num=int(input('几张(30份)\n'))

print('-----------1、 生成细线迷宫-----------')
import sys
import matplotlib.pyplot as plt
from random import randint
import os

# 保存多少张图?
for i in range(num):
	WIDTH  = 30
	HEIGHT = 21
	sys.setrecursionlimit(WIDTH * HEIGHT)

	def initVisitedList():
		visited = []
		for y in range(HEIGHT):
			line = []
			for x in range(WIDTH):
				line.append(False)
			visited.append(line)
		return visited

	def drawLine(x1, y1, x2, y2):
		plt.plot([x1, x2], [y1, y2], color="black")

	def removeLine(x1, y1, x2, y2):
		plt.plot([x1, x2], [y1, y2], color="white")

	def get_edges(x, y):
		result = []
		result.append((x, y, x, y+1))
		result.append((x+1, y, x+1, y+1))
		result.append((x, y, x+1, y))
		result.append((x, y+1, x+1, y+1))

		return result

	def drawCell(x, y):
		edges = get_edges(x, y)
		for item in edges:
			drawLine(item[0], item[1], item[2], item[3])

	def getCommonEdge(cell1_x, cell1_y, cell2_x, cell2_y):
		edges1 = get_edges(cell1_x, cell1_y)
		edges2 = set(get_edges(cell2_x, cell2_y))
		for edge in edges1:
			if edge in edges2:
				return edge
		return None

	def initEdgeList():
		edges = set()
		for x in range(WIDTH):
			for y in range(HEIGHT):
				cellEdges = get_edges(x, y)
				for edge in cellEdges:
					edges.add(edge)
		return edges

	def isValidPosition(x, y):
		if x < 0 or x >= WIDTH:
			return False
		elif y < 0 or y >= HEIGHT:
			return False
		else:
			return True

	def shuffle(dX, dY):
		for t in range(4):
			i = randint(0, 3)
			j = randint(0, 3)
			dX[i], dX[j] = dX[j], dX[i]
			dY[i], dY[j] = dY[j], dY[i]

	def DFS(X, Y, edgeList, visited):
		dX = [0,  0, -1, 1]
		dY = [-1, 1, 0,  0]
		shuffle(dX, dY)
		for i in range(len(dX)):
			nextX = X + dX[i]
			nextY = Y + dY[i]
			if isValidPosition(nextX, nextY):
				if not visited[nextY][nextX]:
					visited[nextY][nextX] = True
					commonEdge = getCommonEdge(X, Y, nextX, nextY)
					if commonEdge in edgeList:
						edgeList.remove(commonEdge)
					DFS(nextX, nextY, edgeList, visited)

	edgeList = initEdgeList()
	visited  = initVisitedList()
	DFS(0, 0, edgeList, visited)
	edgeList.remove((0, 0, 0, 1))
	edgeList.remove((WIDTH, HEIGHT-1, WIDTH, HEIGHT))

	figure = plt.figure(figsize=(29.7,21))  # 创建一个指定大小的图像窗口
	ax = plt.Axes(figure, [0., 0., 1., 1.], frame_on=False)  # 创建一个坐标轴,覆盖整个图像窗口
	figure.add_axes(ax)
	ax.axis('off')  # 关闭坐标轴显示

	for edge in edgeList:
		drawLine(edge[0], edge[1], edge[2], edge[3])

	# 新建图片文件夹,保存所有生成的迷宫图
	path=r'C:\Users\jg2yXRZ\OneDrive\桌面\细线迷宫图图片'
	folder_path = path+r'\01迷宫图'
	os.makedirs(folder_path, exist_ok=True)

	
	plt.savefig(folder_path+r'\{}.png'.format('%02d'%i), dpi=400)  # 保存迷宫图像为maze.png,设置dpi参数调整图像质量
	
	plt.close()  # 超过20张图片会提示占内存,所以关闭图像窗口释放内存
# plt.show()

# print('-----------2、PNG上加箭头----------')


from PIL import Image
import os

# 箭头图片路径
arrow_image_path = path + r'\00箭头.png'

# 调整后的箭头图片大小
new_arrow_size = (400, 200)  # 替换为你想要的箭头图片尺寸


# #1张横版的左下箭头 (300,7730)   4张横版的右上箭头 (11150, 450)
p1=[300,11150]
p2=[7730,450]

for r in range(len(p1)):
	#  遍历图片文件夹
	for filename in os.listdir(folder_path):
		if filename.endswith('.png'):
			# 打开原始图片
			image_path = os.path.join(folder_path, filename)
			image = Image.open(image_path)

			# 打开箭头图片并调整大小
			arrow_image = Image.open(arrow_image_path)
			arrow_image = arrow_image.resize(new_arrow_size)			

			# 如果箭头图片模式不是RGBA,则转换为RGBA模式以保留透明度信息
			if arrow_image.mode != 'RGBA':
				arrow_image = arrow_image.convert('RGBA')

			# 在指定位置添加箭头图片
			position = (int(p1[r]), int(p2[r]))  # 替换为你想要添加箭头图片的位置坐标
			image.paste(arrow_image, position, mask=arrow_image)

			# 保存修改后的图片
			new_image_path = os.path.join(folder_path, filename)
			image.save(new_image_path)

			# 关闭图片对象
			image.close()
			arrow_image.close()


print('-----------3、 导入word,合并png----------')

import os,time
from docx import Document
from docx.shared import Cm, RGBColor
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml.ns import qn
from docx2pdf import convert
from PyPDF2 import PdfMerger

# 设置路径和文件夹名称

folder_path ='迷宫图所有图片文件夹路径'
path=r'C:\Users\jg2yXRZ\OneDrive\桌面\细线迷宫图图片'
folder_path = path+r'\01迷宫图'
template_path = path+r"\01迷宫图细线(A4横版1张横图).docx"# 模板文件路径
output_path =path+r'\零时Word'# 生成docx和PDF的文件夹,最后要删除

# 创建输出文件夹
if not os.path.exists(output_path):
    os.makedirs(output_path)

n = 1
# 遍历图片文件夹
for filename in os.listdir(folder_path):
    if filename.endswith('.png'):
        # 打开模板文档
        doc = Document(template_path)
        
        # 获取第一个表格
        table = doc.tables[0]
        
        # 在表格中插入图片
        table.cell(0, 0).paragraphs[0].add_run().add_picture(os.path.join(folder_path, filename), width=Cm(29.7), height=Cm(20.93))
        
        # 保存为Word文档
        doc.save(os.path.join(output_path, '{:02d}.docx'.format(n)))
        time.sleep(3)
        # 转换为PDF
        convert(os.path.join(output_path, '{:02d}.docx'.format(n)), os.path.join(output_path, '{:02d}.pdf'.format(n)))
        n += 1
	
# 合并PDF
pdf_lst = [os.path.join(output_path, filename) for filename in os.listdir(output_path) if filename.endswith('.pdf')]
pdf_lst.sort()

file_merger = PdfMerger()
for pdf in pdf_lst:
    file_merger.append(pdf)

file_merger.write(path+fr'\01(打印合集)迷宫图(A4横版整页1份横图)({num}份).pdf')
time.sleep(5)

# file_merger.write(os.path.join(output_path, '合并后的PDF.pdf'))
file_merger.close()

# 删除临时文件夹
import shutil
shutil.rmtree(output_path)
shutil.rmtree(folder_path)


图片生成过程

544c3bb466914df2a44586bb79ec0247.png

5fbdeed3ddd9469db77451e1a5378f21.png

cb1346bf30c14acc940ba7103f89df3f.png

dcba73dcab224c90bec86f0081c88701.png

有箭头的图片插入PDF

afd08dbc1fa445b29dd4940df295eb38.png

f61d2f60f8e2426f8aa55400d44a145d.png

最终效果

30af760010d341b5a84c78a5369529fd.png

每个箭头的位置都是一样的(因为已经做成了图片)

8bfd419669cf4e409ef8093c7357dacd.png

b608a0fb1c0b4a529333bbf013e71ff3.png

4f5d700141e54a6f87b323e0921af8a7.png


 

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿夏reasonsummer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值