Adding Images to a Slide in a PPT using Java
In Java, using createPicture() method from XSLFSlide, images can be added to the PPT. Now the computer doesn’t understand, what’s there in the picture, so internally, this method accepts the image in a byte array format —> (a series of non-understandable random numbers, letters, symbols, etc.) something like this, AGETRDYDC5545#$^NHVGCFFSFSFGSDF#@@?.0976*).
The syntax for an empty slideshow
XMLSlideShow ppt = new XMLSlideShow();
The syntax for creating slide
XSLFSlide slide = ppt.createSlide();
The next task is to read the image file, which we wish to insert, and then convert it into a byte array using IOUtils.toByteArray() —> IOUtils class.
Add image into the presentation, using addPicture():
- Byte array format of the picture which is to be added(written in the code as byte[] photo)
- A static variable, which represents the file format of the image.
Syntax:
int idx = ppt.addPicture(photo, XSLFPictureData.PICTURE_TYPE_PNG);
Insert the image to a slide, using createPicture().
XSLFPictureShape pic = slide.createPicture(idx);
Implementation:
Java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFPictureData;
import org.apache.poi.xslf.usermodel.XSLFPictureShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
public class InsertingImage {
public static void main(String args[])
throws IOException
{
XMLSlideShow ppt = new XMLSlideShow();
XSLFSlide slide = ppt.createSlide();
File image
byte [] photo = IOUtils.toByteArray(
new FileInputStream(image));
int idx = ppt.addPicture(
photo, XSLFPictureData.PICTURE_TYPE_PNG);
XSLFPictureShape pic = slide.createPicture(idx);
File file = new File( "insertingimg.pptx" );
FileOutputStream out = new FileOutputStream(file);
ppt.write(out);
System.out.println( "image is inserted" );
out.close();
}
}
|
Commands for Compilation and Execution:
$javac InsertingImage.java
$java InsertingImage
Output:
Reordering of the slides is done.
Last Updated :
28 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...