Search code examples
pythonpython-imaging-librarysyspython-pptx

how can I add two different images to my code?


I'm trying to add two different images (png) to my code and The result shows me the same image twice,I tried to add the different image to the same code but it showed me an error, I tried to change the names of the function but did not giveת I tried to download the image under a different name, how can I solve it? this is my code :

from pptx import Presentation
from pptx.chart.data import CategoryChartData
from pptx.enum.chart import XL_CHART_TYPE
from pptx.util import Inches, Pt
from pptx.dml.color import RGBColor
from pptx.chart.data import  ChartData
import matplotlib.pyplot as plt
import pandas as pd
import sys
from SQLConnector import SQLConnector
import seaborn as sns
from pptx.util import Inches
from PIL import Image


def px_to_inches(path):
    im = Image.open(path)
    width = im.width / im.info['dpi'][0]
    height = im.height / im.info['dpi'][1]

    return (width, height)


def sick_percentage():
    bi_sql = SQLConnector(db='bi')
    sql_query = "<some query>"
    data_from_bi = bi_sql.query_by_str(sql_query)
    return data_from_bi

df = sick_percentage()

prs = Presentation()
# create presentation with 1 slide ------
slide = prs.slides.add_slide(prs.slide_layouts[5])


# define chart data ---------------------

title = slide.shapes.title

title.text = "<title>"


# define chart data ---------------------



fig, ax1 = plt.subplots()

ax2 = ax1.twinx()

df.plot(x='date', y='positives', kind='bar', color='orange', ax=ax1)

df['percent_positive'].plot(x='date', kind='line', marker='d', ax=ax2)


ax1.yaxis.tick_right()

ax2.yaxis.tick_left()

plt.savefig('graph.png')

img = px_to_inches('graph.png')


slide_size = (16, 9)

left = Inches(slide_size[0] - img[0]) / 5.5

top = Inches(slide_size[1] - img[1]) / 2

pic = slide.shapes.add_picture('graph.png', left, top)

img = px_to_inches('pkar.png')


slide_size = (4,5)

left = Inches(slide_size[0] - img[0]) / 10

top = Inches(slide_size[1] - img[1]) / 2

pic = slide.shapes.add_picture('pkar.png', left, top)


prs.save('chart-01.pptx')

Solution

  • I don't know exactly how these modules work, but I think your problem is due to setting img and pic to the two different images.

    I would guess that the presentation isn't saved until you call prs.save, and at that point it renders all of the slides. When this is called, img and pic both refer to pkar.png.

    It might be a better practice to always name the pic/img based on the slide number, ie first slide has img1 and pic1, second slide has img2 and pic2, etc. Better yet, give them informative names, like "img_graph" and "pic_graph", or even better "img_pi_graph_users", etc. That way you aren't overwriting variables, and if you end up with much longer code, the variables are named in a way that you don't have to look back to what you set them to previously.