Manipulating Metafiles

Converting Metafiles to Other Image Formats

Using Aspose.Imaging for Java, developers can convert EMF and WMF (placeable and unplaceable) metafiles to other supported image formats. This topic explains the approach to load existing metafiles and convert them to other image format such as PNG and BMP.

Converting EMF to BMP using File Path Location

Aspose.Imaging for Java provides the EmfMetafileImage class to load EMF files and same can be used to save the image in BMP format by passing an instance of BMPOptions class to the EmfMetafileImage.save method.

Below provided sample code uses the File Location Path to load and save the files on disk.

// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load a Metafile in an instance of EmfMetafileImage class
EmfMetafileImage metafile = new EmfMetafileImage(filePath);
// Save image to BMP using BmpOptions object
metafile.save(dataDir + "ConvertEMFtoBMPusingFilePathLocation_out.bmp", new BmpOptions());

Converting EMF to PNG using Byte Array

Sometimes developers may need to load the images from an Array of Bytes to process them using Aspose.Imaging for Java API. In order to accomplish such requirements, EmfMetafileImage class provides a constructor accepting an object of InputStream, and an overload version on EmfMetafileImage.save method accepting an object of OutputStream.

Below provided sample code demonstrates the usage of Aspose.Imaging for Java API to load and save the images using Array of Bytes.

// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
byte[] bytes = Files.readAllBytes(Paths.get(dataDir + "picture1.emf"));
// Load array of bytes into an instance of ByteArrayInputStream
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
// Use the instance of ByteArrayInputStream to load the image into an
// instance of EmfMetafileImage
EmfMetafileImage metafile = new EmfMetafileImage(inputStream);
// Create an instance of ByteArrayOutputStream to store the results
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// Save the EMF to ByteArrayOutputStream in PNG format
// by passing an instance of PngOptions class as second parameter to
// save method
metafile.save(outputStream, new PngOptions());
// Convert the data in ByteArrayOutputStream to an array of bytes
byte[] outputBytes = outputStream.toByteArray();

Converting EMF To PDF

Using Aspose.Imaging for Java, developers can convert EMF metafile to PDF format. This topic explains the approach to load existing metafiles and convert it to PDF.

Aspose.Imaging for Java provides the EmfImage class to load EMF files and same can be used to save the image to PDF format.

Below provided sample code demonstrate how to convert EMF to PDF.

// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String[] filePaths = new String[] { dataDir + "FilledRectangleRotateMode_c.emf", dataDir + "image5.emf",
dataDir + "LinearGradientBrushCircuitMode.emf", dataDir + "Pict.emf", dataDir + "Picture1.emf",
dataDir + "test.emf", dataDir + "wrong-font-size.emf" };
for (String filePath : filePaths) {
String outPath = filePath + "ConvertEMFtoPDF_out" + ".pdf";
com.aspose.imaging.fileformats.emf.EmfImage image = (com.aspose.imaging.fileformats.emf.EmfImage) com.aspose.imaging.fileformats.emf.EmfImage.load(filePath);
try {
com.aspose.imaging.system.io.FileStream outputStream = new com.aspose.imaging.system.io.FileStream(
outPath, com.aspose.imaging.system.io.FileMode.Create);
try {
if (!image.getHeader().getEmfHeader().getValid()) {
throw new com.aspose.imaging.coreexceptions.ImageLoadException(
"The file" + outPath + " is not valid");
}
com.aspose.imaging.imageoptions.EmfRasterizationOptions emfRasterization = new com.aspose.imaging.imageoptions.EmfRasterizationOptions();
emfRasterization.setPageWidth(image.getWidth());
emfRasterization.setPageHeight(image.getHeight());
emfRasterization.setBackgroundColor(com.aspose.imaging.Color.getWhiteSmoke());
PdfOptions pdfOptions = new PdfOptions();
pdfOptions.setVectorRasterizationOptions(emfRasterization);
image.save(outputStream.toOutputStream(), pdfOptions);
} finally {
outputStream.close();
outputStream.dispose();
}
} finally {
image.dispose();
}
}

Cropping EMF Image

This article demonstrates the usage of Aspose.Imaging for Java API to crop Metafiles. Aspose.Imaging for Java has exposed the crop method for MetafileImage class that can be used to perform cropping on Metafiles.

The Aspose.Imaging for Java API supports two different approaches to Metafile cropping: by shifts and rectangle.

Cropping by Shifts

The MetafileImage class provides an overload of the crop method that accepts 4 integer values denoting Left, Right, Top & Bottom. Based on these four values, the crop method moves the image boundaries toward the center of the image while discarding the outer portion.

The code snippet below demonstrates how to crop an image by shifts.

// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String[] filePaths = new String[] { dataDir + "FilledRectangleRotateMode_c.emf", dataDir + "image5.emf",
dataDir + "LinearGradientBrushCircuitMode.emf", dataDir + "Pict.emf", dataDir + "Picture1.emf",
dataDir + "test.emf", dataDir + "wrong-font-size.emf" };
for (String filePath : filePaths) {
String outPath = filePath + "ConvertEMFtoPDF_out" + ".pdf";
com.aspose.imaging.fileformats.emf.EmfImage image = (com.aspose.imaging.fileformats.emf.EmfImage) com.aspose.imaging.fileformats.emf.EmfImage.load(filePath);
try {
com.aspose.imaging.system.io.FileStream outputStream = new com.aspose.imaging.system.io.FileStream(
outPath, com.aspose.imaging.system.io.FileMode.Create);
try {
if (!image.getHeader().getEmfHeader().getValid()) {
throw new com.aspose.imaging.coreexceptions.ImageLoadException(
"The file" + outPath + " is not valid");
}
com.aspose.imaging.imageoptions.EmfRasterizationOptions emfRasterization = new com.aspose.imaging.imageoptions.EmfRasterizationOptions();
emfRasterization.setPageWidth(image.getWidth());
emfRasterization.setPageHeight(image.getHeight());
emfRasterization.setBackgroundColor(com.aspose.imaging.Color.getWhiteSmoke());
PdfOptions pdfOptions = new PdfOptions();
pdfOptions.setVectorRasterizationOptions(emfRasterization);
image.save(outputStream.toOutputStream(), pdfOptions);
} finally {
outputStream.close();
outputStream.dispose();
}
} finally {
image.dispose();
}
}

Cropping by Rectangle

The MetafileImage class provides another overloaded version of the crop method that accepts an instance of the Rectangle class. You can cut out any portion of an image by providing the desired boundaries to the Rectangle object.

The code snippet below demonstrates how.

// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
MetafileImage metaImage = (MetafileImage) Image.load(dataDir + "Picture1.emf");
// Create an instance of Rectangle class with desired size
Rectangle rectangle = new Rectangle(10, 10, 100, 100);
// Perform the crop operation on object of Rectangle class
metaImage.crop(rectangle);
// Save the result in PNG format
metaImage.save(dataDir + "CropbyRectangle_out.png", new PngOptions());

The crop feature works only for export to raster format. In case the resultant image is stored back in Metafile format the crop method will have no effect.

Export MetaFile To Raster Formats

Using Aspose.Imaging for Java, developers can convert metafile (Emf/Emf+) to raster formats. This article shows how to export/convert metafile file to raster image formats with Aspose.Imaging.

Converting EMF to All Raster Image Formats

It is easy to export metafiles with Aspose.Imaging for Java API. All you need is an object of the appropriate class from com.aspose.imaging.imageoptions package. By using these classes, you can easily export any EMF loaded with Aspose.Imaging for Java to any supported raster image format. Below is an example that demonstrates this simple procedure.

In the example, an EMF image is loaded by passing the file path as a parameter to the Image.load method. It is then exported to various image formats using the EmfMetafileImage ctor.

The examples here show how to load an EMF and save it to BMP, JPEG, PNG, GIF and finally TIFF using Aspose.Imaging for Java.

// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Save EMF to BMP using BmpOptions object
metafile.save(dataDir + "ConvertEMFtoAllRasterImageFormats_out.bmp", new BmpOptions());
// Save EMF to JPG using JpegOptions object
metafile.save(dataDir + "ConvertEMFtoAllRasterImageFormats_out.jpg", new JpegOptions());
// Save EMF to PNG using PngOptions object
metafile.save(dataDir + "ConvertEMFtoAllRasterImageFormats_out.png", new PngOptions());
// Save EMF to GIF using GifOptions object
metafile.save(dataDir + "ConvertEMFtoAllRasterImageFormats_out.gif", new GifOptions());
// Save EMF to TIFF using TiffOptions object with default settings
metafile.save(dataDir + "ConvertEMFtoAllRasterImageFormats_out.tiff", new TiffOptions(TiffExpectedFormat.Default));

Converting Emf/Emf+ to Raster images

Using Aspose.Imaging for Java, developers can convert metafile (Emf/Emf+) to raster formats. This article shows how to export/convert metafile file to raster image formats with Aspose.Imaging.

Aspose.Imaging for Java provides the EmfImage class to load EMF files and same can be used to convert the Emf to raster formats.

Below provided sample code demonstrate how to convert Emf/Emf+ to raster images.

// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String filePath = dataDir + "Picture1.emf";
// Create EmfRasterizationOption class instance and set properties
com.aspose.imaging.imageoptions.EmfRasterizationOptions emfRasterizationOptions = new com.aspose.imaging.imageoptions.EmfRasterizationOptions();
emfRasterizationOptions.setBackgroundColor(com.aspose.imaging.Color.getPapayaWhip());
emfRasterizationOptions.setPageWidth(300);
emfRasterizationOptions.setPageHeight(300);
// Load an existing EMF file as iamge and convert it to EmfImage class
// object
com.aspose.imaging.fileformats.emf.EmfImage image = (com.aspose.imaging.fileformats.emf.EmfImage) com.aspose.imaging.Image
.load(filePath);
// Convert EMF to BMP
com.aspose.imaging.imageoptions.BmpOptions objBMPo = new com.aspose.imaging.imageoptions.BmpOptions();
objBMPo.setVectorRasterizationOptions(emfRasterizationOptions);
image.save(filePath + "_out.bmp", objBMPo);
// Convert EMF to GIF
com.aspose.imaging.imageoptions.GifOptions objGIFo = new com.aspose.imaging.imageoptions.GifOptions();
objGIFo.setVectorRasterizationOptions(emfRasterizationOptions);
image.save(filePath + "_out.gif", objGIFo);
// Convert EMF to JPEG
com.aspose.imaging.imageoptions.JpegOptions objJPEGo = new com.aspose.imaging.imageoptions.JpegOptions();
objJPEGo.setVectorRasterizationOptions(emfRasterizationOptions);
image.save(filePath + "_out.jpeg", objJPEGo);
// Convert EMF to J2K
com.aspose.imaging.imageoptions.Jpeg2000Options objJpeg2o = new com.aspose.imaging.imageoptions.Jpeg2000Options();
objJpeg2o.setVectorRasterizationOptions(emfRasterizationOptions);
image.save(filePath + "_out.j2k", objJpeg2o);
// Convert EMF to PNG
com.aspose.imaging.imageoptions.PngOptions objPNGo = new com.aspose.imaging.imageoptions.PngOptions();
objPNGo.setVectorRasterizationOptions(emfRasterizationOptions);
image.save(filePath + "_out.png", objPNGo);
// Convert EMF to PSD
com.aspose.imaging.imageoptions.PsdOptions objPSDo = new com.aspose.imaging.imageoptions.PsdOptions();
objPSDo.setVectorRasterizationOptions(emfRasterizationOptions);
image.save(filePath + "_out.psd", objPSDo);
// Convert EMF to TIFF
com.aspose.imaging.imageoptions.TiffOptions objTIFFo = new com.aspose.imaging.imageoptions.TiffOptions(
TiffExpectedFormat.TiffLzwRgb);
objTIFFo.setVectorRasterizationOptions(emfRasterizationOptions);
image.save(filePath + "_out.tiff", objTIFFo);
// Convert EMF to WebP
com.aspose.imaging.imageoptions.WebPOptions objWebPo = new com.aspose.imaging.imageoptions.WebPOptions();
objWebPo.setVectorRasterizationOptions(emfRasterizationOptions);
image.save(filePath + "_out.webp", objWebPo);

Specifying Font Folder While Converting

Using Aspose.Imaging for Java, developers can specify the font folder path used while converting CAD (DXF) files. This topic explains the approach to specify the font folder that should be used.

Aspose.Imaging for Java provides the FontSettings class to manage font settings. Using FontSettings class you can specify the font folder that should be used while converting CAD (DXF) file. Note that this allows to add folder with TrueType fonts that will have the priority over other fonts on the system.

Below is the complete syntax to access the FontSettings class and set the font folder.

// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String fonts = Paths.get(System.getProperty("user.home"), "Fonts").toString();
System.out.println("Adding fonts from user's home directory: " + fonts);
FontSettings.addFontsFolder(fonts);
System.out.println("List of all fonts:");
for (String f : FontSettings.getAllFonts()) {
System.out.println("\t" + f);
}

Watermarking Metafiles

This article demonstrates the usage of Aspose.Imaging for Java API to watermark Metafiles. Aspose.Imaging for Java has exposed the getWatermarkDrawer method for all classes that represent Metafiles.

The getWatermarkDrawer method returns an instance of Graphics2D object which allows to create custom watermarks.

The following code example demonstrates how to watermark EMF images and store the result in raster image format.

import com.aspose.imaging.*;
import com.aspose.imaging.fileformats.emf.EmfImage;
import com.aspose.imaging.fileformats.emf.graphics.EmfRecorderGraphics2D;
// load an existing EMF with Image.Load
try (Image image = Image.load("template.emf"))
{
// create and initialize an instance of EmfRecorderGraphics2D class
EmfRecorderGraphics2D graphics = EmfRecorderGraphics2D.fromEmfImage((EmfImage) image);
// create an instance of Font. Initialize it with Font Face, Size and Style
Font font = new Font("Times New Roman", 20, FontStyle.Bold);
// draw the string on image
graphics.drawString("CONFIDENTIAL", font, Color.getRed(), 0, 30);
EmfImage image2 = graphics.endRecording();
// save output to disc
image2.save("output.emf");
}

The getWatermarkDrawer method is available for EmfMetafileImage, MetafileImage and WmfMetafileImage classes.

Adding Raster Images to EMF Images

This article demonstrates the usage of Aspose.Imaging for Java API to add raster images to EMF images.

Aspose.Imaging for Java has exposed the EmfMetafileImage.createEmfRecorderGraphics method that returns an instance of EmfRecorderGraphics2D that in turn can be used to call the drawImage method while specifying the instance of Image to be inserted in EMF image.

The following code example demonstrates how to add a raster image to EMF file.

// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
Image image = Image.load(dataDir + "aspose-logo.jpg");
try {
// Store the DPI value
float dpi = 200f;
// Create an instance of Rectangle to store the dimensions of the
// destination image
java.awt.Rectangle rectange = new java.awt.Rectangle(0, 0, image.getWidth(), image.getHeight());
// Create an instance of Dimension to store the dimensions of the
// source image
java.awt.Dimension dimension = new java.awt.Dimension(image.getWidth(), image.getHeight());
// Create an instance of EmfRecorderGraphics2D
EmfRecorderGraphics2D emfRecorderGraphics = EmfMetafileImage.createEmfRecorderGraphics(rectange, dimension,
dpi, dpi);
// Draw the source image starting from top left corner
emfRecorderGraphics.drawImage(image, 0, 0, null);
// Create an instance of EmfMetafileImage
EmfMetafileImage emfMetafileImage = emfRecorderGraphics.endRecording();
// Save the result
emfMetafileImage.save(dataDir + "AddRasterImagestoEMFImages_out.emf");
} finally {
image.dispose();
}

Getting Font Information

Using Aspose.Imaging for Java, developers can get information about the font used in the WMF file while converting WMF file. This topic explains, how one can get information about missing fonts and how to get the list of all fonts used in the WMF file.

Aspose.Imaging for Java provides the FontSettings class to get font information. FontSettings provides the functionality to get

  • A list of font names accessible to Aspose.Imaging API.
  • A list of font names used in the metafile.
  • A list of font names that are missing in the environment with respect to WMF file loaded.

Below is the complete syntax to access the FontSettings class and get the font information.

// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
System.out.println("Get list of font names accessible to Aspose.Imaging API");
for (String f : FontSettings.getAllFonts()) {
System.out.println("\t" + f);
}
System.out.println("Get list of font names used in the metafile");
MetafileImage metafile = new EmfMetafileImage(dataDir + "Sample1.emf");
for (String f : metafile.getUsedFonts()) {
System.out.println("\t" + f);
}
System.out.println("Get list of font names that are missing");
for (String f : metafile.getMissedFonts()) {
System.out.println("\t" + f);
}

Specifying Substitute Fonts

Using Aspose.Imaging for Java, developers can specify the substitute fonts instead of original font while converting WMF file. This topic explains the approach how to specify the substitute fonts.

Aspose.Imaging for Java provides the FontSettings class to manage font settings. Using FontSettings class you can specify the substitute fonts that should be used instead of original one while converting WMF file. Method addFontSubstitutes can be used that takes in originalFontName string as first parameter and an array of strings substituteFontNames as second parameter.

Below is the complete syntax to access the FontSettings class and supply the substitute Fonts.

// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String[] substituteFontName = { "font1", "font2" };
com.aspose.imaging.FontSettings.addFontSubstitutes("originalFontName", substituteFontName);

Applying Font Settings For Metafiles

Using Aspose.Imaging for Java, developers can add fonts folder path into the existing font folder settings used while converting metafiles (EMF) files. This topic explains the approach to apply the font settings that should be used while converting metafiles.

Aspose.Imaging for Java provides the FontSettings class to manage font settings. Using FontSettings class you can specify the font folder that should be used while converting metafiles (EMF).

Below is the complete syntax to access the FontSettings class and set/add the font folder path.

Managing resources while saving Metafile as SVG

Using Aspose.Imaging for Java, developers can manage resources (fonts and internal images) when saving Metafile images (emf and wmf) into SVG file stream. This topic explains that there should be a setting that will let us specify whether to save contained image as a separate file and provide a stream for saving it, or to embed image as base64 string inside of SVG. The following code snippet demonstrates the usage of Aspose.Imaging for Java API to manage resources.

// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
private static final String ImageFolderName = "Images";
private static final String OutFolderName = "Out\\";
private static final String SourceFolder = "C:\\Temp\\Errors\\7\\";
private static String OutFolder = SourceFolder + OutFolderName;
private static String ImageFolder = OutFolder + "\\" + ImageFolderName;
public void saveWithEmbeddedImages() throws Exception
{
String[] files = new String[]
{
"auto.svg"
};
for (int i = 0; i < files.length; i++)
{
this.save(true, files[i], null);
}
}
public void saveWithExportImages() throws Exception
{
String[] files = new String[]
{
"auto.svg"
};
String[][] expectedImages = new String[][]
{
new String[]
{
"svg_img1.png", "svg_img10.png", "svg_img11.png","svg_img12.png",
"svg_img13.png", "svg_img14.png", "svg_img15.png", "svg_img16.png",
"svg_img2.png", "svg_img3.png", "svg_img4.png", "svg_img5.png",
"svg_img6.png","svg_img7.png", "svg_img8.png", "svg_img9.png"
},
};
for (int i = 0; i < files.length; i++)
{
this.save(false, files[i], expectedImages[i]);
}
}
private void save(final boolean useEmbedded, String fileName, String[] expectedImages) throws Exception
{
File f = new File(OutFolder);
if (!f.exists())
{
f.mkdir();
}
String fontStoreType = useEmbedded ? "Embedded" : "Stream";
String inputFile = SourceFolder + fileName;
String outFileName = fileName + "_" + fontStoreType + ".svg";
String outputFile = OutFolder + "\\" + outFileName;
Image image = Image.load(inputFile);
final String imageFolder;
try
{
final EmfRasterizationOptions emfRasterizationOptions = new EmfRasterizationOptions();
emfRasterizationOptions.setBackgroundColor(Color.getWhite());
emfRasterizationOptions.setPageWidth(image.getWidth());
emfRasterizationOptions.setPageHeight(image.getHeight());
final String testingFileName = inputFile.substring(inputFile.lastIndexOf("\\")+1, inputFile.length() - 4);
imageFolder = ImageFolder + "\\" + testingFileName;
image.save(outputFile,
new SvgOptions()
{{
setVectorRasterizationOptions(emfRasterizationOptions);
setCallback(
new SvgCallbackImageTest(useEmbedded, imageFolder)
{{
setLink(ImageFolderName +"/"+testingFileName);
}});
}});
}
finally
{
image.dispose();
}
if (!useEmbedded)
{
f = new File(imageFolder);
String[] files = f.list();
if (files.length != expectedImages.length)
{
throw new RuntimeException(String.format(
"Expected count image files = %d, Current count image files = %d", expectedImages.length,
files.length));
}
for (int i = 0; i < files.length; i++)
{
String file = files[i];
if (file == null || file.isEmpty())
{
throw new Exception(String.format("Expected file name: %s, current is empty", expectedImages[i]));
}
if (!file.equalsIgnoreCase(expectedImages[i]))
{
throw new Exception(String.format("Expected file name: '%s', current: '%s'", expectedImages[i], file));
}
}
}
}
}
class SvgCallbackImageTest extends SvgResourceKeeperCallback
{
/**
* The out folder
*/
private final String outFolder;
/**
* The use embedded font
*/
private final boolean useEmbeddedImage;
/**
* The font counter
*/
private int fontCounter = 0;
public SvgCallbackImageTest(boolean useEmbeddedImage, String outFolder)
{
this.useEmbeddedImage = useEmbeddedImage;
this.outFolder = outFolder;
File f = new File(outFolder);
if (f.exists())
{
File[] list = f.listFiles();
for (File it : list)
it.delete();
f.delete();
}
}
private String link;
public String getLink()
{
return link;
}
public void setLink(String link)
{
this.link = link;
}
public String onImageResourceReady(byte[] imageData, int imageType, String suggestedFileName, boolean[] useEmbeddedImage)
{
useEmbeddedImage[0] = this.useEmbeddedImage;
if (this.useEmbeddedImage)
{
return suggestedFileName;
}
String imageFolder = this.outFolder;
File f = new File(imageFolder);
if (!f.exists())
{
f.mkdirs();
}
String name = suggestedFileName;
name = name.substring(name.indexOf('\\')+1);
String fileName = imageFolder + "\\" + name;
try
{
FileOutputStream fs = new FileOutputStream(fileName);
try
{
fs.write(imageData);
}
finally
{
fs.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
return "./" + this.getLink() + "/" + suggestedFileName;
}

Support For Replacing Missing Fonts

Using Aspose.Imaging for Java, developers can replace missing fonts when saving ODG, SVG and MetaFile images. This topic explains the approach to replace the fonts that should be used. The following code snippet demonstrates the usage of Aspose.Imaging for Java API to replace the font while saving ODG images.

// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
private static final String ImageFolderName = "Images";
private static final String OutFolderName = "Out\\";
private static final String SourceFolder = "C:\\Temp\\Errors\\7\\";
private static String OutFolder = SourceFolder + OutFolderName;
private static String ImageFolder = OutFolder + "\\" + ImageFolderName;
public void saveWithEmbeddedImages() throws Exception
{
String[] files = new String[]
{
"auto.svg"
};
for (int i = 0; i < files.length; i++)
{
this.save(true, files[i], null);
}
}
public void saveWithExportImages() throws Exception
{
String[] files = new String[]
{
"auto.svg"
};
String[][] expectedImages = new String[][]
{
new String[]
{
"svg_img1.png", "svg_img10.png", "svg_img11.png","svg_img12.png",
"svg_img13.png", "svg_img14.png", "svg_img15.png", "svg_img16.png",
"svg_img2.png", "svg_img3.png", "svg_img4.png", "svg_img5.png",
"svg_img6.png","svg_img7.png", "svg_img8.png", "svg_img9.png"
},
};
for (int i = 0; i < files.length; i++)
{
this.save(false, files[i], expectedImages[i]);
}
}
private void save(final boolean useEmbedded, String fileName, String[] expectedImages) throws Exception
{
File f = new File(OutFolder);
if (!f.exists())
{
f.mkdir();
}
String fontStoreType = useEmbedded ? "Embedded" : "Stream";
String inputFile = SourceFolder + fileName;
String outFileName = fileName + "_" + fontStoreType + ".svg";
String outputFile = OutFolder + "\\" + outFileName;
Image image = Image.load(inputFile);
final String imageFolder;
try
{
final EmfRasterizationOptions emfRasterizationOptions = new EmfRasterizationOptions();
emfRasterizationOptions.setBackgroundColor(Color.getWhite());
emfRasterizationOptions.setPageWidth(image.getWidth());
emfRasterizationOptions.setPageHeight(image.getHeight());
final String testingFileName = inputFile.substring(inputFile.lastIndexOf("\\")+1, inputFile.length() - 4);
imageFolder = ImageFolder + "\\" + testingFileName;
image.save(outputFile,
new SvgOptions()
{{
setVectorRasterizationOptions(emfRasterizationOptions);
setCallback(
new SvgCallbackImageTest(useEmbedded, imageFolder)
{{
setLink(ImageFolderName +"/"+testingFileName);
}});
}});
}
finally
{
image.dispose();
}
if (!useEmbedded)
{
f = new File(imageFolder);
String[] files = f.list();
if (files.length != expectedImages.length)
{
throw new RuntimeException(String.format(
"Expected count image files = %d, Current count image files = %d", expectedImages.length,
files.length));
}
for (int i = 0; i < files.length; i++)
{
String file = files[i];
if (file == null || file.isEmpty())
{
throw new Exception(String.format("Expected file name: %s, current is empty", expectedImages[i]));
}
if (!file.equalsIgnoreCase(expectedImages[i]))
{
throw new Exception(String.format("Expected file name: '%s', current: '%s'", expectedImages[i], file));
}
}
}
}
}
class SvgCallbackImageTest extends SvgResourceKeeperCallback
{
/**
* The out folder
*/
private final String outFolder;
/**
* The use embedded font
*/
private final boolean useEmbeddedImage;
/**
* The font counter
*/
private int fontCounter = 0;
public SvgCallbackImageTest(boolean useEmbeddedImage, String outFolder)
{
this.useEmbeddedImage = useEmbeddedImage;
this.outFolder = outFolder;
File f = new File(outFolder);
if (f.exists())
{
File[] list = f.listFiles();
for (File it : list)
it.delete();
f.delete();
}
}
private String link;
public String getLink()
{
return link;
}
public void setLink(String link)
{
this.link = link;
}
public String onImageResourceReady(byte[] imageData, int imageType, String suggestedFileName, boolean[] useEmbeddedImage)
{
useEmbeddedImage[0] = this.useEmbeddedImage;
if (this.useEmbeddedImage)
{
return suggestedFileName;
}
String imageFolder = this.outFolder;
File f = new File(imageFolder);
if (!f.exists())
{
f.mkdirs();
}
String name = suggestedFileName;
name = name.substring(name.indexOf('\\')+1);
String fileName = imageFolder + "\\" + name;
try
{
FileOutputStream fs = new FileOutputStream(fileName);
try
{
fs.write(imageData);
}
finally
{
fs.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
return "./" + this.getLink() + "/" + suggestedFileName;
}