.add_picture in python-pptx changes the description of the image from the given one to image.png

Viewed 86

Use-case: I make a presentation in python-pptx and then manually go in and add some slide and then remember that I need to change one or more of the pictures. Then I want to be able to run the program again and have it replace the picture with the same name.

My problem is that sometimes it works, usually the first time, and the picture is replaced with the same descr but more often then not, it is replaced with image.png and because of this i am unable to find that picture the next time I try to replace. Does any one has any ideas? Here is my replace function:

   def replace(self, newPic):
    for slide in self.pres.slides:
        for shape in slide.shapes:
            try:
                if shape._pic.nvPicPr.cNvPr.get('descr') == newPic:
                    top, left, width, height = shape.top, shape.left, shape.width, shape.height
                    self.deleteShape(shape)
                    img = slide.shapes.add_picture(self.inDir + "/" + newPic, left, top, width, height)
                    imgDescr = img._pic.nvPicPr.cNvPr.get('descr')
                   
            except AttributeError:
                pass

I also tried the following,

def replace(self, newPic):
    #If in list with every figure
    for slide in self.pres.slides:
        for shape in slide.shapes:
            try:
                if shape._pic.nvPicPr.cNvPr.get('descr') == newPic:
                    imgPic = shape._pic
                    imgRID = imgPic.xpath('./p:blipFill/a:blip/@r:embed')[0]
                    imgPart = shape.part.relatedpart(imgRID)

                    with open(self.inDir + "/" + newPic, 'rb') as f:
                        rImgBlob = f.read()

                    # replace
                    imgPart._blob = rImgBlob
            except AttributeError:
                pass

However here i got an attribute error

imgPart = shape.part.relatedpart(imgRID) AttributeError: 'SlidePart' object has no attribute 'relatedpart'

0 Answers
Related