Copy slide with images python pptx - image

My end goal is to change the theme of a presentation. To do this, I have created a source template and new template (with the correct theme). I iterate over each slide in the source template then add a new slide to the new template with the contents of the source using the code below - source. If there is a better way to do this I'd love to hear it.
This works great for text and text boxes, however the test image cannot be displayed in the new powerpoint (show in the image below):
Code
def copy_slide_from_external_prs(self, src, idx, newPrs):
# specify the slide you want to copy the contents from
src_slide = src.slides[idx]
# Define the layout you want to use from your generated pptx
slide_layout = newPrs.slide_layouts[2]
# create now slide, to copy contents to
curr_slide = newPrs.slides.add_slide(slide_layout)
# remove placeholders
for p in [s.element for s in curr_slide.shapes if 'Text Placeholder' in s.name or 'Title' in s.name]:
p.getparent().remove(p)
# now copy contents from external slide, but do not copy slide properties
# e.g. slide layouts, etc., because these would produce errors, as diplicate
# entries might be generated
for shp in src_slide.shapes:
el = shp.element
newel = copy.deepcopy(el)
curr_slide.shapes._spTree.insert_element_before(newel, 'p:extLst')
return newPrs
I was trying many different solutions and tried creating a new Picture using the image.blob property in the source image. However, then the image does not have an element. Do I need to convert the blob to a PNG, save it, then create a new image using that saved PNG?
There must be a better way to do this. Again, I just want to change the theme.
Thanks in advance!

Here is the workaround I developed. I first check if the shape is an image, and if it is, I write the image to a local directory. Then I add a picture to the slide using that saved image. Finally, I delete the locally saved image.
Now this copy_slide function works for images:
def copy_slide_from_external_prs(src, idx, newPrs):
# specify the slide you want to copy the contents from
src_slide = src.slides[idx]
# Define the layout you want to use from your generated pptx
SLD_LAYOUT = 5
slide_layout = prs.slide_layouts[SLD_LAYOUT]
# create now slide, to copy contents to
curr_slide = newPrs.slides.add_slide(slide_layout)
# create images dict
imgDict = {}
# now copy contents from external slide, but do not copy slide properties
# e.g. slide layouts, etc., because these would produce errors, as diplicate
# entries might be generated
for shp in src_slide.shapes:
if 'Picture' in shp.name:
# save image
with open(shp.name+'.jpg', 'wb') as f:
f.write(shp.image.blob)
# add image to dict
imgDict[shp.name+'.jpg'] = [shp.left, shp.top, shp.width, shp.height]
else:
# create copy of elem
el = shp.element
newel = copy.deepcopy(el)
# add elem to shape tree
curr_slide.shapes._spTree.insert_element_before(newel, 'p:extLst')
# add pictures
for k, v in imgDict.items():
curr_slide.shapes.add_picture(k, v[0], v[1], v[2], v[3])
os.remove(k)

Using code from #Michael-Berk I made very elegant method for copying slides (including images). Check this answer: https://stackoverflow.com/a/73954830/20159015

Related

Writing Macro in ImageJ to open, change color, adjust brightness and resave microscope images

I'm trying to write a code in Image J that will:
Open all images in separate windows that contains "488" within a folder
Use look up tables to convert images to green and RGB color From ImageJ, the commands are: run("Green"); and run("RGB Color");
Adjust the brightness and contrast with defined values for Min and Max (same values for each image).
I know that the code for that is:
//run("Brightness/Contrast..."); setMinAndMax(value min, value max); run("Apply LUT");
Save each image in the same, original folder , in Tiff and with the same name but finishing with "processed".
I have no experience with Java and am very bad with coding. I tried to piece something together using code I found on stackoverflow and on the ImageJ website, but kept getting error codes. Any help is much appreciated!
I don't know if you still need it, but here is an example.
output_dir = "C:/Users/test/"
input_dir = "C:/Users/test/"
list = getFileList(input_dir);
listlength = list.length;
setBatchMode(true);
for (z = 0; z < listlength; z++){
if(endsWith(list[z], 'tif')==true ){
if(list[z].contains("488")){
title = list[z];
end = lengthOf(title)-4;
out_path = output_dir + substring(title,0,end) + "_processed.tif";
open(input_dir + title);
//add all the functions you want
run("Brightness/Contrast...");
setMinAndMax(1, 15);
run("Apply LUT");
saveAs("tif", "" + out_path + "");
close();
};
run("Close All");
}
}
setBatchMode(false);
I think it contains all the things you need. It opens all the images (in specific folder) that ends with tif and contains 488. I didn't completely understand what you want to do with each photo, so I just added your functions. But you probably won't have problems with adding more/different since you can get them with macro recorder.
And the code is written to open tif files. If you have tiff just be cerful that you change that and also change -4 to -5.

poster image not displaying with add_movie() in python-pptx

I am trying to insert some sound files into a presentation, and the sound file seems to save fine, but the display image is always the default play button logo. Is there something wrong with my code, or is it another issue. I am currently working in a linux environment, if that makes any difference. I have tried with both mp4 and mp3 and the image issue is the same. The small play bar also seems not to appear although the sound file is in the presentation.
from pptx import Presentation
from pptx.util import Inches
prs = Presentation()
title_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_slide_layout)
prs.slides[0].shapes.add_movie("sample2.mp3",
left = Inches(1), top = Inches(1), width = Inches(1), height = Inches(1),
poster_frame_image = "cat.jpeg"
)
prs.save('sound_image.pptx')
You can easily add any sound files to presentations and set poster images for them by using Aspose.Slides for Python as shown below:
import aspose.slides as slides
presentation_path = "example.pptx"
audio_path = "sample2.mp3"
image_path = "cat.jpeg"
with slides.Presentation() as presentation:
slide = presentation.slides[0]
# Add an audio frame to the slide with a specified position and size.
with open(audio_path, 'rb') as audio_stream:
audio_frame = slide.shapes.add_audio_frame_embedded(150, 100, 50, 50, audio_stream)
# Add the image to presentation resources.
with open(image_path, 'rb') as image_stream:
audio_image = presentation.images.add_image(image_stream)
# Set the image as the audio poster.
audio_frame.picture_format.picture.image = audio_image
presentation.save(presentation_path, slides.export.SaveFormat.PPTX)
I work as a Support Developer at Aspose.

My toplevel window in tkinter is no longer being destroyed. It was working fine until I tried changing other aspects of my function

I'm trying to get a popup window to display random text and a picture every time a button is pressed in tkinter. My original code was going to use an if/elif statement to do this. It worked as intended but I thought it might be easier to pair the data in a dictionary since there would be 50 elif statements otherwise (is it frowned upon to use so many? I actually found it easier to read).I was able to get this working but now the toplevel window in tkinter is not being destroyed like it was in the original function. A new Label is just being created on top of it and I can't figure out why. The function code is below. Thanks in advance, any help would be appreciated!
def Add_Gemstone2():
global Addstone
#destroy the previous window if there is one.
try:
AddStone.destroy()
except(AttributeError, NameError):
pass
#create the window.
AddStone=Toplevel()
AddStone.configure(bg='White', height=200, width=325)
AddStone.geometry('325x180+10+100')
# add gemstones to list from file.
gem_stones = open('gemstones.txt')
all_gem_stones = gem_stones.readlines()
gemstones = []
for i in all_gem_stones:
gemstones.append(i.rstrip())
# Add pictures to list.
path = r'C:\Users\Slack\Desktop\PYTHON WORKS\PYTHON GUI PROJECT\gems'
gempictures = []
# r=root, d=directories, f = files
for r,d,f in os.walk(path):
for file in f:
if '.gif' in file:
gempictures.append(os.path.join(r, file))
#create dictionary from lists.
gemdiction = dict(zip(gemstones, gempictures))
key, val = random.choice(list(gemdiction.items()))
# create the labels.
glbl1 = Label(AddStone, text=key, bg='gold', wraplength=300)
glbl1.pack()
image = ImageTk.PhotoImage(Image.open(val))
glbl2 = Label(AddStone, image=image)
glbl2.image = image
glbl2.pack()

Working on more than one image in Matlab

I started to learn Matlab newly. I am trying to learn about classification. I will make classification for my 23 images. In my function file I am using
I = imread('img.jpg');
a = rgb2gray(I);
bw = double(imread('mask_img.jpg'))/255;
b = rgb2gray(bw);
bwi = 1-b;
And working on the original image and ground truth of the image. I can handle one image and I have loop in the my main file.
for i=1:original_images_db.Count
original = original_images_db.ImageLocation(i);
groundtruth = original_file;
[x,y] = calculateFeatures(original, groundtruth, parameters);
dataset.HorizonFeats{i} = features;
end
And i related original_images_db with imageset to files. When i run my main file, naturally everytime it reads img from function file but actually in command file main can detect other images. My question is how can i make a loop in my function file so my data can be in all other images?
Thank you
fname={'1.jpg','2.jpg','3.jpg'};
create cell like that, it contains all file-path of images
for i=1: length(fname)
im= imread(fname{i});
end
and now you can iterate the all images
or
use dir(image_path) function
fnames = dir('image_directory_path');

How to remove link tag from image using Nokogiri

I'm parsing an HTML document using Nokogiri. The code contain several images like this:
<img alt="alternative-text" border="0" height="427" src="http://url_to_my_photo.jpg?" title="Image Title" width="640">
I'm trying to save that image to my S3 storage, change the style and remove the link. All the images have the css tag ".post-body img".
So far, the closest I got is this:
#doc.css(".post-body img").each do |image|
#new_photo = Photo.create!(
#Params required to save and upload the photo to S3.
...
...
)
# The url of the photo upload to S3 is #new_photo.photo.url
image['src']= #new_photo.photo.url
image['class'] = "my-picture-class"
image.parent['src] = '#'
puts image.parent.content
#doc.to_html
end
This removes the link to the big photo but obviously it isn't a good solution.
I've tried to replace the parent using image.parent << image as suggested on http://rubyforge.org/pipermail/nokogiri-talk/2009-June/000333.html but doesn't do anything and image.parent = image returns "Could not reparent node (RuntimeError)"
To convert that mailing list example over to apply to your situation, you have to remember that node is the node they are trying to get rid of, which in your case is image.parent.
So instead of image.parent['src] = '#' you should try:
link = image.parent
link.parent << image
link.remove
Edit:
Actually, the above code would probably move all the images to the bottom of whatever element contains the link, so try this instead:
link = image.parent
link.replace(image)

Resources