此程序很简单,是利用ezdxf库的脚本程序实现,将.dxf文件转化为png图片,非常的简单,具体参考:
https://ezdxf.readthedocs.io/en/stable/addons/drawing.html
https://github.com/destroT/dxf2image
添加python库:
from argparse import FileType
import os
import ezdxf
import PIL
from PIL import Image
import matplotlib
from ezdxf import recover
from ezdxf import DXFStructureError
from ezdxf.addons.drawing import RenderContext, Frontend
from ezdxf.addons.drawing.matplotlib import MatplotlibBackend
from tkinter import filedialog
若没有ezdxf库可以用:pip install ezdxf 进行安装
安装tkinter是为了打开文件对话框,获取文件路径
基本原理:使用ezdxf先转png图片,再把png转换成bmp,这里这么做是为了项目中的需求
def dxf2image(dxffile, destination_name):
#print(matplotlib.__file__)#获取库路径
#print(os.path.dirname(dxffile))#获取文件夹路径
try:
doc, auditor = recover.readfile(dxffile)
except IOError as e:
raise IOError("Not a DXF file or a generic I/O error.") from e
except DXFStructureError as e:
raise DXFStructureError("Invalid or corrupted DXF file.") from e
# The auditor.errors attribute stores severe errors,
# which may raise exceptions when rendering.
if not auditor.has_errors:
s_path = os.path.dirname(dxffile)
print(s_path)
fig = matplotlib.pyplot.figure(facecolor = "white")#创建绘图窗口
fig.patch.set_facecolor('white')
ax = fig.add_axes([0, 0, 1, 1])#利用这四个参数,我们可以在原来设定的画板上的任意位置进行贴图
ctx = RenderContext(doc)#启动插件绘图
#ctx.current_layout_properties.set_colors(bg='#FFFFFF')
ezdxf.addons.drawing.properties.MODEL_SPACE_BG_COLOR = '#FFFFFF'
out = MatplotlibBackend(ax)#启动插件绘图
Frontend(ctx, out).draw_layout(doc.modelspace(), finalize=True)
destination_name = s_path+'/'+destination_name
print(destination_name)
fig.savefig(destination_name, dpi=300,facecolor='white',transparent=True)#保存为对应的文件,也可以是PDF等
matplotlib.pyplot.show()#在此暂停,防止退出
#os.path.split(os.path.realpath())
img = Image.open(destination_name)#读取图片
print(img.height,img.width)
if img.width > 200 and img.width>img.height:
ratio = img.width/200
new_img = img.convert('RGB')#转成RGB
new_img = new_img.resize((200,(int)(img.height/ratio)))
print(s_path+'ware.bmp')
new_img.save(s_path+'/ware.bmp','bmp')
print(1)
elif img.height > 200 and img.width<img.height:
ratio = img.height/200
new_img = img.convert('RGB')
new_img = new_img.resize(((int)(img.width/ratio),200))
print(s_path+'ware.bmp')
new_img.save(s_path+'/ware.bmp','bmp')
print(2)
else:
new_img = img.convert('RGB')
new_img = new_img.resize(img.size)
print(s_path+'ware.bmp')
new_img.save(s_path+'/ware.bmp','bmp')
print(3)
if __name__ == "__main__":
dxf2image(filedialog.askopenfilename(filetypes = [("DXF",".dxf")]) ,"raster.png")
首先打开dxf文件,然后调用ezdxf库的脚本进行转换,ezdxf库会利用matplotlib进行绘图,然后对窗口进行截图保存。
zdxf.addons.drawing.properties.MODEL_SPACE_BG_COLOR = '#FFFFFF'
这段代码是把背景换成我自己项目所需要的颜色,可以删除,删除后就是默认的背景颜色
img = Image.open(destination_name)#读取图片
这句代码之后的将png图片转换为等比像素大小的bmp图片