arg*_*rgo 5 python python-docx
我正在尝试使用python-docx库从.docx文件中获取图像索引.我能够提取图像的名称,图像的高度和宽度.但不是它在word文件中的索引
import docx
doc = docx.Document(filename)
for s in doc.inline_shapes:
print (s.height.cm,s.width.cm,s._inline.graphic.graphicData.pic.nvPicPr.cNvPr.name)
Run Code Online (Sandbox Code Playgroud)
产量
21.228 15.920 IMG_20160910_220903848.jpg
Run Code Online (Sandbox Code Playgroud)
事实上,我想知道是否有更简单的方法来获取图像名称,例如s.height.cm以cm为单位获取高度.我的主要要求是了解图像在文档中的位置,因为我需要提取图像并对其进行一些处理,然后再将图像放回到同一位置
sca*_*nny 10
API不直接支持此操作.
但是,如果你愿意深入挖掘内部结构并使用底层lxmlAPI,那么它是可能的.
一般方法是访问与ImagePart要检查和修改的图片对应的实例,然后读取和写入._blob属性(将图像文件保存为字节).
这个标本XML可能会有所帮助:http: //python-docx.readthedocs.io/en/latest/dev/analysis/features/shapes/picture.html#specimen-xml
从包含图片的内联形状,你得到这个<a:blip>元素:
blip = inline_shape._inline.graphic.graphicData.pic.blipFill.blip
Run Code Online (Sandbox Code Playgroud)
关系id(r:id通常,但r:在这种情况下嵌入)可在以下位置获得:
rId = blip.embed
Run Code Online (Sandbox Code Playgroud)
然后,您可以从文档部分获取图像部分
document_part = document.part
image_part = document_part.related_parts[rId]
Run Code Online (Sandbox Code Playgroud)
然后二进制图像可用于读取和写入._blob.
如果您编写新的blob,它将在保存时替换先前的图像.
在扩展到单个文档中的多个图像之前,您可能希望让它使用单个图像并感受它.
可能存在一个或两个缓存的图像特征,因此在保存并重新加载文件之前,您可能无法获得所有更精细的点,因此请保持警惕.
不是因为你可以看到的胆小的心脏,但如果你想要它足够糟糕并且可以通过代码追踪:)应该工作:)
小智 5
您还可以使用简单的循环检查段落,并检查哪个 xml 包含图像(例如,如果 xml 包含“graphicData”),即哪个是图像容器(您可以对运行执行相同的操作):
from docx import Document
image_paragraphs = []
doc = Document(path_to_docx)
for par in doc.paragraphs:
if 'graphicData' in par._p.xml:
image_paragraphs.append(par)
Run Code Online (Sandbox Code Playgroud)
与解压缩 docx 文件相比,图像位于“images”文件夹中,并且它们的顺序与 image_paragraphs 列表中的顺序相同。在每个段落元素上,您都有许多选项来更改它。如果您想提取 img 对其进行处理并将其插入到同一位置,那么
paragraph.clear()
paragraph.add_run('your description, if needed')
run = paragraph.runs[0]
run.add_picture(path_to_pic, width, height)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4427 次 |
| 最近记录: |