Working with Images in PS file | Java
Add Image in PS Document
The Aspose.Page for Java library offers two methods for adding images to a PS document:
- for opaque images;
- for transparent images;
This was done because PostScript doesn’t support transparency. However, translucent images can be rendered as a set of fully transparent and fully opaque pixels. Such images are called masks.
If we want to see the translucent image in the PS document as a mask that will better reflect the transparency of the image, we should do some checking and preprocessing of such an image. The check and preprocessing require time. Therefore, if one is sure that the image is fully opaque, it is better to use the first method, as it saves execution time.
The second method recognizes whether the image is fully opaque, fully transparent, or translucent. If it is fully opaque, it is added as the opaque image in the first method; if it is fully transparent, it is not added to the document at all; if it is a translucent image, it is added as a PostScript image mask.
In the example below, we demonstrate how to add a fully opaque image. Adding a transparent image will be demonstrated in the “Working with Transparency” article.
In order to add an image to a new PsDocument with the Aspose.Page for Java library in this example, we take the following steps:
- Create an output stream for the resulting PS file.
- Create a PsSaveOptions object with default options.
- Create a 1-paged PsDocument with the already created output stream and save options.
- Create a new graphics state.
- Create java.awt.image.BufferedImage from an image file.
- Create the necessary transformation for the image.
- Add the image to the PsDocument object.
- Exit from the current graphics state to the upper-level one.
- Close the page.
- Save the document.
1// Add image to PS document.
2
3String outputFileName = "AddImage_outPS.ps";
4
5//Create save options with A4 size
6PsSaveOptions options = new PsSaveOptions();
7
8// Create new 1-paged PS Document
9PsDocument document = new PsDocument(getOutputDir() + outputFileName, options, false);
10
11document.writeGraphicsSave();
12document.translate(100, 100);
13
14//Create a BufferedImage object from image file
15try {
16 BufferedImage image = ImageIO.read(new java.io.File(getDataDir() + "TestImage Format24bppRgb.jpg"));
17
18 //Create image transform
19 AffineTransform transform = new AffineTransform();
20 transform.translate(35, 300);
21 transform.scale(3, 3);
22 transform.rotate(Math.toRadians(-45));
23
24 //Add image to document
25 document.drawImage(image, transform, Color.WHITE);
26} catch (IOException ex) {
27}
28
29document.writeGraphicsRestore();
30
31//Close current page
32document.closePage();
33
34//Save the document
35document.save();See working with images in PS documents in .NET.
The result of running this code appears as follows:

You can download examples and data files from GitHub.