如何使用tempfile将IPython.core.display.Image转换为base64字符串?
解决IPython Image对象转base64的AttributeError问题
你遇到的AttributeError: 'Image' object has no attribute 'get_figure'是因为IPython的Image类只是用于Notebook中显示图片的包装类,并非matplotlib的figure对象,自然没有get_figure()方法。
其实完全不需要绕IPython的Image这一步,直接用pydotplus生成的graph数据就能转换成base64字符串,甚至连临时文件都可以不用(如果你的需求只是拿到base64的话)。下面是两种可行的解决方案:
方案一:直接将graph生成的二进制数据转base64(推荐)
这是最简洁高效的方式,跳过所有不必要的中间环节:
import base64 from sklearn import tree import pydotplus # 生成决策树的dot数据和graph对象 dot_data = tree.export_graphviz( model.best_estimator_[0], out_file=None, feature_names=X_train.columns, class_names=unique_target ) graph = pydotplus.graph_from_dot_data(dot_data) # 直接获取PNG二进制数据,转成base64字符串 png_binary = graph.create_png() base64_str = base64.b64encode(png_binary).decode('utf-8')
这样你就直接得到了可以用于网页嵌入或其他场景的base64编码字符串,完全不需要临时文件或者IPython的Image对象。
方案二:用tempfile临时文件中转(如果必须用临时文件)
如果你因为某些原因一定要通过临时文件来转换,注意不要用IPython的Image对象操作,直接将graph的PNG数据写入临时文件即可:
import tempfile import base64 import os from sklearn import tree import pydotplus # 生成dot数据和graph dot_data = tree.export_graphviz( model.best_estimator_[0], out_file=None, feature_names=X_train.columns, class_names=unique_target ) graph = pydotplus.graph_from_dot_data(dot_data) # 使用NamedTemporaryFile(TemporaryFile在Windows下可能无法同时读写) with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_file: # 将graph生成的PNG数据写入临时文件 tmp_file.write(graph.create_png()) # 读取临时文件内容并转base64 with open(tmp_file.name, 'rb') as f: base64_str = base64.b64encode(f.read()).decode('utf-8') # 手动删除临时文件(因为delete=False) os.unlink(tmp_file.name)
关键总结
你的核心误区是试图把IPython的Image显示对象当成可操作的图像文件对象来处理,实际上pydotplus的graph对象本身就可以直接生成PNG二进制数据,直接用这个数据转换base64才是正确的路径。
内容的提问来源于stack exchange,提问作者Harshwardhan Nandedkar
相关产品推荐
相关产品推荐

