Images and Shapes

Overview

This guide shows how to insert pictures into a Word document, size them in points, find and export them again, and what happens with SVG with Aspose.Words FOSS for Java. You can insert a picture into a Word document from a file, a stream, a byte array or a BufferedImage with DocumentBuilder.insertImage, give it a size in points, and find it again later. A picture is a Shape node: insertImage returns it, Shape.hasImage tells whether it holds an image and Shape.getImageData returns an ImageData that reports the image type and its size in pixels and points. In a test on Java 8, 17 and 21, the overloads that take a file name, an InputStream, a byte array and a BufferedImage each inserted a picture. The examples create their own test images with javax.imageio.ImageIO, so no image file is needed, and were compiled and run against the published package on Java 8, 17 and 21 with -Djava.awt.headless=true.


Prerequisites

RequirementDetail
Java8 or later
DependencyThe package from Installation
Importimport com.aspose.words.*;
CodeThe examples are statements. Put them in a method that declares throws Exception.

Insert Pictures From a File and a Stream

The example writes a 120 by 60 pixel PNG with ImageIO, then inserts it three times: from the file name, from an InputStream with a width and height of 60 and 30, and as a floating picture with RelativeHorizontalPosition.PAGE, RelativeVerticalPosition.PAGE and WrapType.SQUARE. The first picture came out 90 by 45 points. The image reported 96 dpi, and the size in points was the size in pixels times 0.75 (the factor follows the resolution the image reports); the next example shows the same factor for a 400 by 100 pixel PNG (300 by 75 points). The saved file stores the size in EMU: in a test a 120 by 30 point picture was written as <wp:extent cx="1524000" cy="381000" />, which is 12700 EMU per point. The floating picture printed inline false, a square wrap, left 300 and top 400. After saving and reloading, getChildNodes(NodeType.SHAPE, true) found 3 shapes, all with an image of type PNG, 120 by 60 pixels, and the alternative text set with setAlternativeText came back as Company logo. In a test, the saved file stored that text in the descr attribute of the picture’s wp:docPr element.

import com.aspose.words.*;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;

BufferedImage logo = new BufferedImage(120, 60, BufferedImage.TYPE_INT_RGB);
Graphics2D g = logo.createGraphics();
g.setColor(new Color(30, 90, 160));
g.fillRect(0, 0, 120, 60);
g.setColor(Color.WHITE);
g.fillRect(10, 10, 40, 40);
g.dispose();
ImageIO.write(logo, "png", new File("logo.png"));

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.writeln("From a file, natural size:");
Shape natural = builder.insertImage("logo.png");
natural.setAlternativeText("Company logo");
builder.writeln();

builder.writeln("From a stream, scaled to 60 x 30 points:");
InputStream in = new FileInputStream("logo.png");
Shape small = builder.insertImage(in, 60, 30);
in.close();
builder.writeln();

builder.writeln("Floating, positioned on the page:");
Shape floating = builder.insertImage("logo.png", RelativeHorizontalPosition.PAGE, 300,
        RelativeVerticalPosition.PAGE, 400, 90, 45, WrapType.SQUARE);
System.out.println("natural: " + natural.getWidth() + " x " + natural.getHeight() + " points, inline " + natural.isInline());
System.out.println("small: " + small.getWidth() + " x " + small.getHeight() + " points, inline " + small.isInline());
System.out.println("floating: inline " + floating.isInline() + ", wrap square " + (floating.getWrapType() == WrapType.SQUARE)
        + ", left " + floating.getLeft() + ", top " + floating.getTop());
doc.save("logos.docx");

Document reloaded = new Document("logos.docx");
NodeCollection shapes = reloaded.getChildNodes(NodeType.SHAPE, true);
System.out.println("Shapes after reload: " + shapes.getCount());
for (int i = 0; i < shapes.getCount(); i++) {
    Shape shape = (Shape) shapes.get(i);
    ImageData data = shape.getImageData();
    System.out.println(i + ": has image " + shape.hasImage()
            + ", type " + ImageType.getName(data.getImageType())
            + ", " + data.getImageSize().getWidthPixels() + " x " + data.getImageSize().getHeightPixels() + " pixels"
            + ", shown " + shape.getWidth() + " x " + shape.getHeight() + " points"
            + ", inline " + shape.isInline()
            + ", alt '" + shape.getAlternativeText() + "'");
}

The program printed:

natural: 90.0 x 45.0 points, inline true
small: 60.0 x 30.0 points, inline true
floating: inline false, wrap square true, left 300.0, top 400.0
Shapes after reload: 3
0: has image true, type PNG, 120 x 60 pixels, shown 90.0 x 45.0 points, inline true, alt 'Company logo'
1: has image true, type PNG, 120 x 60 pixels, shown 60.0 x 30.0 points, inline true, alt ''
2: has image true, type PNG, 120 x 60 pixels, shown 90.0 x 45.0 points, inline false, alt ''

Find the Pictures, Export Them and Resize Them

getChildNodes(NodeType.SHAPE, true) returns every shape, not only pictures: in a test a rectangle created with new Shape(doc, ShapeType.RECTANGLE) and added with insertNode was returned too, and hasImage was false for it and true for the pictures, so test hasImage before you use getImageData. The example reloads a document with a PNG and a JPEG, prints the type and the pixel and point sizes of each, exports each picture with ImageData.save and compares the exported file with the file that was inserted: both were identical. It then calls setWidth(120) on the pictures wider than 120 points. A new picture has getAspectRatioLocked true, and the height followed: 300 by 75 points became 120 by 30, while the 48 by 48 point picture was left alone.

import com.aspose.words.*;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Files;
import java.util.Arrays;
import javax.imageio.ImageIO;

// Build a document with two pictures: a wide PNG and a square JPEG.
String[] names = {"banner.png", "badge.jpg"};
int[] widths = {400, 64};
int[] heights = {100, 64};
Document source = new Document();
DocumentBuilder builder = new DocumentBuilder(source);
for (int i = 0; i < names.length; i++) {
    BufferedImage img = new BufferedImage(widths[i], heights[i], BufferedImage.TYPE_INT_RGB);
    Graphics2D g = img.createGraphics();
    g.setColor(i == 0 ? new Color(200, 80, 20) : new Color(20, 120, 60));
    g.fillRect(0, 0, widths[i], heights[i]);
    g.dispose();
    ImageIO.write(img, i == 0 ? "png" : "jpg", new File(names[i]));
    builder.insertImage(names[i]);
    builder.writeln();
}
source.save("gallery.docx");

// Reload, list every picture, export it and shrink the wide ones to 120 points.
Document doc = new Document("gallery.docx");
NodeCollection shapes = doc.getChildNodes(NodeType.SHAPE, true);
for (int i = 0; i < shapes.getCount(); i++) {
    Shape shape = (Shape) shapes.get(i);
    if (!shape.hasImage()) {
        continue;
    }
    ImageData data = shape.getImageData();
    String type = ImageType.getName(data.getImageType());
    String exported = "exported-" + i + "." + type.toLowerCase();
    data.save(exported);
    boolean identical = Arrays.equals(Files.readAllBytes(new File(exported).toPath()),
            Files.readAllBytes(new File(names[i]).toPath()));
    System.out.println(type + ": " + data.getImageSize().getWidthPixels() + " x " + data.getImageSize().getHeightPixels()
            + " pixels, shown " + shape.getWidth() + " x " + shape.getHeight() + " points, exported file identical: " + identical);
    if (shape.getWidth() > 120) {
        shape.setWidth(120);
    }
}
doc.save("gallery-small.docx");

Document resized = new Document("gallery-small.docx");
NodeCollection after = resized.getChildNodes(NodeType.SHAPE, true);
for (int i = 0; i < after.getCount(); i++) {
    Shape shape = (Shape) after.get(i);
    System.out.println("after resize " + i + ": " + shape.getWidth() + " x " + shape.getHeight() + " points");
}

The program printed:

PNG: 400 x 100 pixels, shown 300.0 x 75.0 points, exported file identical: true
JPEG: 64 x 64 pixels, shown 48.0 x 48.0 points, exported file identical: true
after resize 0: 120.0 x 30.0 points
after resize 1: 48.0 x 48.0 points

SVG Pictures Are Rejected

In this edition insertImage does not accept an SVG file. In a test on Java 8, 17 and 21 the overloads that take a file name, a stream, a byte array and a file name with a size each threw java.lang.UnsupportedOperationException with the message FOSS. The failed call added no shape to the document: the example printed 0 pictures after it. The example catches the exception and inserts a PNG raster of the same drawing instead, 100 by 50 points, and the reloaded document had 1 picture.

import com.aspose.words.*;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import javax.imageio.ImageIO;

String svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"100\" height=\"50\">"
        + "<rect width=\"100\" height=\"50\" fill=\"#1e5aa0\"/></svg>";
Writer writer = new OutputStreamWriter(new FileOutputStream("logo.svg"), "UTF-8");
writer.write(svg);
writer.close();

// A raster copy of the same drawing, to fall back to.
BufferedImage raster = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);
Graphics2D g = raster.createGraphics();
g.setColor(new Color(0x1e5aa0));
g.fillRect(0, 0, 200, 100);
g.dispose();
ImageIO.write(raster, "png", new File("logo-fallback.png"));

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Logo:");

Shape logo;
try {
    logo = builder.insertImage("logo.svg");
    System.out.println("SVG inserted");
} catch (UnsupportedOperationException e) {
    System.out.println("SVG rejected: " + e.getMessage());
    System.out.println("Pictures in the document after the failed call: "
            + doc.getChildNodes(NodeType.SHAPE, true).getCount());
    logo = builder.insertImage("logo-fallback.png", 100, 50);
}
System.out.println("Inserted " + ImageType.getName(logo.getImageData().getImageType())
        + ", " + logo.getWidth() + " x " + logo.getHeight() + " points");
doc.save("logo.docx");

Document reloaded = new Document("logo.docx");
NodeCollection shapes = reloaded.getChildNodes(NodeType.SHAPE, true);
System.out.println("Pictures after reload: " + shapes.getCount());

The program printed:

SVG rejected: FOSS
Pictures in the document after the failed call: 0
Inserted PNG, 100.0 x 50.0 points
Pictures after reload: 1

Tips and Best Practices

  • Test Shape.hasImage for every shape that getChildNodes(NodeType.SHAPE, true) returns; a shape that is not a picture was returned too and hasImage was false for it.
  • To rescale a picture, set only its width or only its height: a new picture has getAspectRatioLocked true, and in the example setWidth(120) changed the height from 75 to 30 points.
  • Call setAlternativeText on the Shape that insertImage returns, so that the saved file carries the text.

Common Issues

IssueCauseFix
The compiler reports cannot find symbol for Document.The com.aspose.words package is not imported.Add import com.aspose.words.*;.
The compiler reports an unreported exception.The Document constructors, Document.save and some other methods declare throws Exception.Declare it on the calling method or catch it.
insertImage throws UnsupportedOperationException with the message FOSS.The file is an SVG. This edition rejects SVG pictures.Convert the drawing to PNG or JPEG first, as in the third example.
insertImage throws FileNotFoundException with the message Can't find file: missing.png.The file does not exist at the name that was passed.Check the file name and the working directory of the process.
Document.save throws NullPointerException after insertImage(new byte[0]) failed.insertImage with an empty byte array throws NullPointerException but leaves a picture shape without data in the document; on Java 8, 17 and 21 the document then had 1 shape and save threw NullPointerException.Check that the array is not empty before the call.
The picture keeps its old size after getImageData().setImage(...).setImage replaces the image data only. In a test a 48 by 48 point picture stayed 48 by 48 points after a 400 by 100 pixel PNG was loaded into it.Set the width and the height of the Shape again after setImage.

FAQ

Which image formats can I insert?

In tests on Java 8, 17 and 21, PNG, JPEG and GIF files of 80 by 40 pixels written with ImageIO were inserted and read back as 60 by 30 points (80 pixels at 96 dpi), and getImageType returned PNG, JPEG and GIF after a reload. A BMP file written the same way was converted: its type read back as PNG. When the BMP was inserted with insertImage(path, 60, 30) its size was exactly 60 by 30 points; when it was inserted without a size, its width after a reload was 60.00834645669291 points, because the image reports a resolution of about 95.99 dpi. SVG is rejected, as described above.

In which unit are the width and height of a picture?

In points. In a test a picture with getWidth 120 and getHeight 30 was saved with an extent of 1524000 by 381000 EMU, and 12700 EMU are one point.

Do identical pictures use one image part in the file?

In a test, three pictures inserted from the same PNG file were saved with one image part, word/media/image1.png, and all three a:blip elements pointed to it.

How do I get the pixel size of a picture?

Call getImageData().getImageSize() and read getWidthPixels and getHeightPixels; getWidthPoints and getHeightPoints give the size in points.


API Reference Summary

Class / MethodDescription
ShapeRepresents an object in the drawing layer, such as an AutoShape, textbox, freeform, OLE object, ActiveX control, or picture.
ImageDataDefines an image for a shape.
ImageSizeContains information about image size and resolution.
ImageTypeSpecifies the type (format) of an image in a Microsoft Word document.
DocumentBuilder.insertImage(fileName, width, height)Inserts an inline image and scales it to the specified size.
Shape.hasImage()Returns true if the shape has image bytes or links an image.
Shape.getImageData()Provides access to the image of the shape.
ImageData.save(fileName)Saves the image into a file.

Related Guides

See Also