Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active October 18, 2021 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save aspose-com-gists/07be292db0a393dc95f153f84b28c069 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/07be292db0a393dc95f153f84b28c069 to your computer and use it in GitHub Desktop.
Aspose.Imaging for Java
This gist exceeds the recommended number of files (~10). To access all files, please clone this gist.
Gist for Aspose.Imaging for Java
// The path to the documents directory.
String dataDir = "D:/WebPImages/";
// Load GIFF image into the instance of image class.
try (GifImage gif = (GifImage)Image.load(dataDir + "asposelogo.gif"))
{
// Load an existing WebP image into the instance of WebPImage class.
try (WebPImage webp = new WebPImage(gif.getWidth(), gif.getHeight(), null))
{
// Loop through the GIFF frames
for (IGifBlock block : gif.getBlocks())
{
// Convert GIFF block to GIFF Frame
if (!(block instanceof GifFrameBlock))
{
continue;
}
GifFrameBlock gifBlock = (GifFrameBlock) block;
// Create an instance of WebP Frame instance by passing GIFF frame to class constructor.
WebPFrameBlock webBlock = new WebPFrameBlock(gifBlock);
webBlock.setTop((short)gifBlock.getTop());
webBlock.setLeft((short)gifBlock.getLeft());
webBlock.setDuration((short)gifBlock.getControlBlock().getDelayTime());
// Add WebP frame to WebP image block list
webp.addBlock(webBlock);
}
// Set Properties of WebP image.
webp.getOptions().setAnimBackgroundColor(0xff); // Black
webp.getOptions().setAnimLoopCount(0); // Infinity
webp.getOptions().setQuality(50);
webp.getOptions().setLossless(false);
// Save WebP image.
webp.save(dataDir + "ConvertGIFFImageFrame_out.webp");
}
}
import com.aspose.imaging.*;
import com.aspose.imaging.imageoptions.*;
// Image width and height
int width = 500;
int height = 300;
// Where created image to store
String path = "C:/createdImage.png";
// Create options
PngOptions options = new PngOptions();
options.setSource(new FileCreateSource(path, false));
try (PngImage image = (PngImage)Image.create(options, width, height))
{
// Create and initialize an instance of Graphics class
Graphics graphic = new Graphics(image);
// and Clear Graphics surface
graphic.clear(Color.Green);
// Draw line on image
graphic.drawLine(new Pen(Color.getBlue()), 9, 9, 90, 90);
// Resize image
int newWidth = 400;
image.resizeWidthProportionally(newWidth, ResizeType.LanczosResample);
// Crop the image to specified area
Rectangle area = new Rectangle(10, 10, 200, 200);
image.crop(area);
image.save();
}
// The path to the documents directory.
String dataDir = "D:/dataDir/";
// Creates an instance of BmpOptions and set its various properties
BmpOptions imageOptions = new BmpOptions();
imageOptions.setBitsPerPixel(24);
// Define the source property for the instance of BmpOptions Second boolean parameter determines if the file is temporal or not
imageOptions.setSource(new FileCreateSource(dataDir + "CreatingAnImageBySettingPath_out.bmp", false));
try
{
// Creates an instance of Image and call Create method by passing the BmpOptions object
try (Image image = Image.create(imageOptions, 500, 500))
{
image.save(dataDir + "CreatingAnImageBySettingPath1_out.bmp");
}
}
finally
{
imageOptions.close();
}
// The path to the documents directory.
String dataDir = "D:/WebPImages/";
// Create an instance of WebPOptions class and set properties
try (WebPOptions imageOptions = new WebPOptions())
{
imageOptions.setLossless(true);
imageOptions.setSource(new FileCreateSource(dataDir + "CreatingWebPImage_out.webp", false));
// Create an instance of image class by using WebOptions instance that you have just created.
try (Image image = Image.create(imageOptions, 500, 500))
{
image.save();
}
}
import com.aspose.imaging.*;
import com.aspose.imaging.customfonthandler.CustomFontData;
import com.aspose.imaging.imageoptions.PngOptions;
import com.aspose.imaging.imageoptions.VectorRasterizationOptions;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.LinkedList;
import java.util.List;
String dataDir = "C:/folder/";
String[] files = new String[]{"missing-font.emf", "missing-font.odg", "missing-font.wmf", "missing-font.svg"};
for (String file : files)
{
String outputPath = dataDir + file + ".png";
customFontSourceTest(dataDir, dataDir, file, dataDir + "Fonts/");
new File(outputPath).delete();
}
public static void customFontSourceTest(String inputPath, String outputPath, String fileName, String fontPath)
{
LoadOptions loadOptions = new LoadOptions();
loadOptions.addCustomFontSource(new CustomFontSource()
{
@Override
public CustomFontData[] get(Object... objects)
{
return getFontSource(objects);
}
}, fontPath);
try (Image img = Image.load(inputPath + fileName, loadOptions))
{
VectorRasterizationOptions vectorRasterizationOptions =
(VectorRasterizationOptions) img.getDefaultOptions(new Object[]{Color.getWhite(), img.getWidth(), img.getHeight()});
vectorRasterizationOptions.setTextRenderingHint(TextRenderingHint.SingleBitPerPixel);
vectorRasterizationOptions.setSmoothingMode(SmoothingMode.None);
img.save(outputPath + fileName + ".png", new PngOptions()
{{
setVectorRasterizationOptions(vectorRasterizationOptions);
}});
}
}
// The custom fonts provider example.
public static CustomFontData[] getFontSource(Object... args)
{
String fontsPath = "";
if (args.length > 0)
{
fontsPath = args[0].toString();
}
List<CustomFontData> customFontData = new LinkedList<>();
final File[] files = new File(fontsPath).listFiles();
if (files != null)
{
for (File font : files)
{
try
{
customFontData.add(new CustomFontData(getFileNameWithoutExtension(font.getName()), Files.readAllBytes(font.toPath())));
}
catch (IOException e)
{
// Hide errors
}
}
}
return customFontData.toArray(new CustomFontData[0]);
}
private static String getFileNameWithoutExtension(String fileName)
{
return fileName.substring(0, fileName.lastIndexOf('.'));
}
String dataDir = "DataDir/";
String fileName = "skewed.png";
String output = "skewed.out.png";
String inputFileName = dataDir + fileName;
// Get rid of the skewed scan with default parameters
try (RasterImage image = (RasterImage)Image.load(inputFileName))
{
image.normalizeAngle(false /*do not resize*/, Color.getLightGray() /*background color*/);
image.save(dataDir + output);
}
try (TiffImage image = (TiffImage)Image.load("Sample.tif"))
{
for (PathResource path : image.getActiveFrame().getPathResources())
{
System.out.println(path.getName());
}
}
import com.aspose.imaging.Image;
import com.aspose.imaging.PageExportingAction;
import com.aspose.imaging.RasterImage;
import com.aspose.imaging.fileformats.tiff.TiffImage;
import com.aspose.imaging.imageoptions.WebPOptions;
try (TiffImage tiffImage = (TiffImage) Image.load("10MB_Tif.tif"))
{
// Set batch operation for pages
tiffImage.setPageExportingAction(new PageExportingAction()
{
@Override
public void invoke(int pageIndex, Image page)
{
// Fires garbage collection to avoid unnecessary garbage storage from previous pages
System.gc();
((RasterImage)page).rotate(90);
}
});
tiffImage.save("rotated.webp", new WebPOptions());
/* Attention! In batch mode all pages will be released in this line!
If you want to further perform operations on the original image, you should reload it from the source to another instance. */
}
try (Image image = Image.load("Rle4.bmp"))
{
BmpOptions options = new BmpOptions();
options.setCompression(BitmapCompression.Rle4);
options.setBitsPerPixel(4);
options.setPalette(ColorPaletteHelper.create4Bit());
image.save("output.bmp", options);
}
import com.aspose.imaging.*;
import com.aspose.imaging.imageoptions.*;
String inputFileName = "SimpleShapes.cdr";
try (com.aspose.imaging.fileformats.cdr.CdrImage image = (com.aspose.imaging.fileformats.cdr.CdrImage)Image.load(inputFileName))
{
JpegOptions options = new JpegOptions();
// Set rasterization options for fileformat
VectorRasterizationOptions rasterizationOptions = (VectorRasterizationOptions) image.getDefaultOptions(new Object[]{Color.getWhite(), image.getWidth(), image.getHeight()});
rasterizationOptions.setTextRenderingHint(TextRenderingHint.SingleBitPerPixel);
rasterizationOptions.setSmoothingMode(SmoothingMode.None);
options.setVectorRasterizationOptions(rasterizationOptions);
image.save("SimpleShapes.jpg", options);
}
try (VectorMultipageImage image = (VectorMultipageImage)Image.load("MultiPage2.cdr"))
{
// Create page rasterization options
VectorRasterizationOptions[] pageOptions = createPageOptions(CdrRasterizationOptions.class, image);
// Create PDF options
PdfOptions options = new PdfOptions();
MultiPageOptions multiPageOptions = new MultiPageOptions();
multiPageOptions.setPageRasterizationOptions(pageOptions);
options.setMultiPageOptions(multiPageOptions);
// Export image to PDF format
image.save("MultiPage2.cdr.pdf", options);
}
private static <TOptions extends VectorRasterizationOptions>
VectorRasterizationOptions[] createPageOptions(Class<TOptions> type, VectorMultipageImage image)
throws InstantiationException, IllegalAccessException
{
List<VectorRasterizationOptions> list = new LinkedList<VectorRasterizationOptions>();
// Create page rasterization options for each page in the image
for (Image page : image.getPages())
{
list.add(createPageOptions(type, page.getSize()));
}
return list.toArray(new VectorRasterizationOptions[0]);
}
private static <TOptions extends VectorRasterizationOptions>
VectorRasterizationOptions createPageOptions(Class<TOptions> type, Size pageSize) throws IllegalAccessException, InstantiationException
{
// Create the instance of rasterization options
TOptions options = type.newInstance();
// Set the page size
options.setPageSize(Size.to_SizeF(pageSize));
return options;
}
import com.aspose.imaging.*;
import com.aspose.imaging.imageoptions.*;
String inputFileName = "SimpleShapes.cdr";
try (com.aspose.imaging.fileformats.cdr.CdrImage image = (com.aspose.imaging.fileformats.cdr.CdrImage)Image.load(inputFileName))
{
PngOptions options = new PngOptions();
// Set rasterization options for fileformat
VectorRasterizationOptions rasterizationOptions = (VectorRasterizationOptions) image.getDefaultOptions(new Object[]{Color.getWhite(), image.getWidth(), image.getHeight()});
rasterizationOptions.setTextRenderingHint(TextRenderingHint.SingleBitPerPixel);
rasterizationOptions.setSmoothingMode(SmoothingMode.None);
options.setVectorRasterizationOptions(rasterizationOptions);
image.save("SimpleShapes.png", options);
}
import com.aspose.imaging.*;
import com.aspose.imaging.imageoptions.*;
String inputFileName = "MultiPage.cdr";
try (com.aspose.imaging.fileformats.cdr.CdrImage image = (com.aspose.imaging.fileformats.cdr.CdrImage)Image.load(inputFileName))
{
PsdOptions options = new PsdOptions();
// By default if image is multipage image all pages exported
options.setMultiPageOptions(new MultiPageOptions());
// Optional parameter that indicates to export multipage image as one
// layer (page) otherwise it will be exported page to page
options.getMultiPageOptions().setMergeLayers(true);
// Set rasterization options for fileformat
VectorRasterizationOptions rasterizationOptions = (VectorRasterizationOptions) image.getDefaultOptions(new Object[]{Color.getWhite(), image.getWidth(), image.getHeight()});
rasterizationOptions.setTextRenderingHint(TextRenderingHint.SingleBitPerPixel);
rasterizationOptions.setSmoothingMode(SmoothingMode.None);
options.setVectorRasterizationOptions(rasterizationOptions);
image.save("MultiPage.psd", options);
}
import com.aspose.imaging.Image;
import com.aspose.imaging.fileformats.tiff.TiffImage;
import com.aspose.imaging.fileformats.tiff.pathresources.PathResource;
import java.util.List;
import java.util.Optional;
try (TiffImage image = (TiffImage)Image.load("Sample.tif"))
{
// Get path resources from TIFF image
List<PathResource> pathResources = image.getActiveFrame().getPathResources();
// Get resource with clipping path name
Optional<PathResource> first = pathResources.stream().filter(it -> it.getBlockId() == 2999).findFirst();
if (first.isPresent())
{
PathResource clippingPathResource = first.get();
// Change clipping path name
clippingPathResource.setName(pathResources.get(1).getName());
// Update path resources in TIFF image
image.getActiveFrame().setPathResources(pathResources);
// Save changed image
image.save("Sample_changed.tif");
}
}
import com.aspose.imaging.*;
import com.aspose.imaging.imageoptions.JpegOptions;
import com.aspose.imaging.imageoptions.VectorRasterizationOptions;
try (com.aspose.imaging.fileformats.cmx.CmxImage image =
(com.aspose.imaging.fileformats.cmx.CmxImage) Image.load("input.cmx"))
{
JpegOptions options = new JpegOptions();
// Set rasterization options for fileformat
VectorRasterizationOptions rasterizationOptions = (VectorRasterizationOptions) image.getDefaultOptions(new Object[]{Color.getWhite(), image.getWidth(), image.getHeight()});
options.setVectorRasterizationOptions(rasterizationOptions);
rasterizationOptions.setTextRenderingHint(TextRenderingHint.SingleBitPerPixel);
rasterizationOptions.setSmoothingMode(SmoothingMode.None);
image.save("output.pdf", options);
}
import com.aspose.imaging.*;
import com.aspose.imaging.imageoptions.PdfOptions;
import com.aspose.imaging.imageoptions.VectorRasterizationOptions;
try (com.aspose.imaging.fileformats.cmx.CmxImage image =
(com.aspose.imaging.fileformats.cmx.CmxImage)Image.load("input.cmx"))
{
com.aspose.imaging.imageoptions.PdfOptions options = new PdfOptions();
options.setPdfDocumentInfo(new com.aspose.imaging.fileformats.pdf.PdfDocumentInfo());
// Set rasterization options for fileformat
VectorRasterizationOptions rasterizationOptions = (VectorRasterizationOptions) image.getDefaultOptions(new Object[]{Color.getWhite(), image.getWidth(), image.getHeight()});
options.setVectorRasterizationOptions(rasterizationOptions);
rasterizationOptions.setTextRenderingHint(TextRenderingHint.SingleBitPerPixel);
rasterizationOptions.setSmoothingMode(SmoothingMode.None);
image.save("output.pdf", options);
}
static void main() throws IllegalAccessException, InstantiationException
{
try (VectorMultipageImage image = (VectorMultipageImage)Image.load("MultiPage2.cmx"))
{
// Create page rasterization options
VectorRasterizationOptions[] pageOptions = createPageOptions(CmxRasterizationOptions.class, image);
// Create TIFF options
TiffOptions options = new TiffOptions(TiffExpectedFormat.TiffDeflateRgb);
MultiPageOptions multiPageOptions = new MultiPageOptions();
multiPageOptions.setPageRasterizationOptions(pageOptions);
options.setMultiPageOptions(multiPageOptions);
// Export image to TIFF format
image.save("MultiPage2.cmx.tiff", options);
}
}
private static <TOptions extends VectorRasterizationOptions>
VectorRasterizationOptions[] createPageOptions(Class<TOptions> type, VectorMultipageImage image)
throws InstantiationException, IllegalAccessException
{
List<VectorRasterizationOptions> list = new LinkedList<VectorRasterizationOptions>();
// Create page rasterization options for each page in the image
for (Image page : image.getPages())
{
list.add(createPageOptions(type, page.getSize()));
}
return list.toArray(new VectorRasterizationOptions[0]);
}
private static <TOptions extends VectorRasterizationOptions>
VectorRasterizationOptions createPageOptions(Class<TOptions> type, Size pageSize) throws IllegalAccessException, InstantiationException
{
// Create the instance of rasterization options
TOptions options = type.newInstance();
// Set the page size
options.setPageSize(Size.to_SizeF(pageSize));
return options;
}
// The path to the documents directory.
String dataDir = "D:\\DataDir\\";
// Create an instance of JpegOptions and set its various properties
com.aspose.imaging.imageoptions.JpegOptions imageOptions = new com.aspose.imaging.imageoptions.JpegOptions();
try
{
// Create an instance of FileCreateSource and assign it to Source
// property
imageOptions.setSource(new com.aspose.imaging.sources.FileCreateSource(dataDir + "two_images_result_out.jpeg", false));
// Create an instance of Image
com.aspose.imaging.Image image = com.aspose.imaging.Image.create(imageOptions, 600, 600);
try
{
// Create and initialize an instance of Graphics
com.aspose.imaging.Graphics graphics = new com.aspose.imaging.Graphics(image);
// Clear the image surface with white color
graphics.clear(com.aspose.imaging.Color.getWhite());
// Draw Image
try (Image tmp = com.aspose.imaging.Image.load(dataDir + "sample_1.bmp"))
{
graphics.drawImage(tmp, 0, 0, 600, 300);
}
try (Image tmp = com.aspose.imaging.Image.load(dataDir + "File1.bmp"))
{
graphics.drawImage(tmp, 0, 300, 600, 300);
}
// Call save method to save the resultant image.
image.save();
}
finally
{
image.close();
}
}
finally
{
imageOptions.close();
}
// 1.Export compressed formats to raster
String[] files = {"example.emz", "example.wmz", "example.svgz"};
String baseFolder = "D:\\Compressed\\";
for (String file : files)
{
String inputFile = baseFolder + file;
String outFile = inputFile + ".png";
try (final Image image = Image.load(inputFile))
{
final VectorRasterizationOptions vectorRasterizationOptions = (VectorRasterizationOptions)image.getDefaultOptions(new Object[] { Color.getWhite(), image.getWidth(), image.getHeight() });
image.save(outFile, new PngOptions(){{ setVectorRasterizationOptions(vectorRasterizationOptions); }});
}
}
// 2.Export Emz to Emf
String file = "example.emz";
String baseFolder = "D:\\Compressed\\";
String inputFile = baseFolder + file;
String outFile = inputFile + ".emf";
try (final Image image = Image.load(inputFile))
{
final VectorRasterizationOptions vectorRasterizationOptions = new EmfRasterizationOptions() {{ setPageSize(Size.to_SizeF(image.getSize())); }};
image.save(outFile, new EmfOptions(){{ setVectorRasterizationOptions(vectorRasterizationOptions); }});
}
// 3.Export Wmz to Wmf
String file = "example.wmz";
String baseFolder = "D:\\Compressed\\";
String inputFile = baseFolder + file;
String outFile = inputFile + ".wmf";
try (final Image image = Image.load(inputFile))
{
final VectorRasterizationOptions vectorRasterizationOptions = new WmfRasterizationOptions() {{ setPageSize(Size.to_SizeF(image.getSize())); }};
image.save(outFile, new WmfOptions(){{ setVectorRasterizationOptions(vectorRasterizationOptions); }});
}
// 4.Export Svgz to Svg
String file = "example.svgz";
String baseFolder = "D:\\Compressed\\";
String inputFile = baseFolder + file;
String outFile = inputFile + ".svg";
try (final Image image = Image.load(inputFile))
{
final VectorRasterizationOptions vectorRasterizationOptions = new SvgRasterizationOptions() {{ setPageSize(Size.to_SizeF(image.getSize())); }};
image.save(outFile, new SvgOptions(){{ setVectorRasterizationOptions(vectorRasterizationOptions); }});
}
// 5.Export Emf to Emz
String file = "input.emf";
String baseFolder = "D:\\Compressed\\";
String inputFile = baseFolder + file;
String outFile = inputFile + ".emz";
try (final Image image = Image.load(inputFile))
{
final VectorRasterizationOptions vectorRasterizationOptions = new EmfRasterizationOptions() {{ setPageSize(Size.to_SizeF(image.getSize())); }};
image.save(outFile, new EmfOptions(){{ setVectorRasterizationOptions(vectorRasterizationOptions); setCompress(true); }});
}
// 6.Export Wmf to Wmz
String file = "castle.wmf";
String baseFolder = "D:\\Compressed\\";
String inputFile = baseFolder + file;
String outFile = inputFile + ".wmz";
try (final Image image = Image.load(inputFile))
{
final VectorRasterizationOptions vectorRasterizationOptions = new WmfRasterizationOptions() {{ setPageSize(Size.to_SizeF(image.getSize())); }};
image.save(outFile, new EmfOptions(){{ setVectorRasterizationOptions(vectorRasterizationOptions); setCompress(true); }});
}
// 7.Export Svg to Svgz
String file = "juanmontoya_lingerie.svg";
String baseFolder = "D:\\Compressed\\";
String inputFile = baseFolder + file;
String outFile = inputFile + ".svgz";
try (final Image image = Image.load(inputFile))
{
final VectorRasterizationOptions vectorRasterizationOptions = new SvgRasterizationOptions() {{ setPageSize(Size.to_SizeF(image.getSize())); }};
image.save(outFile, new SvgOptions(){{ setVectorRasterizationOptions(vectorRasterizationOptions); setCompress(true); }});
}
// The path to the documents directory.
String dataDir = "dataDir/";
// Load an image through file path location or stream
try (Image image = Image.load(dataDir + "sample.tiff"))
{
// Create an instance of TiffOptions for the resultant image
TiffOptions outputSettings = new TiffOptions(TiffExpectedFormat.Default);
// Set BitsPerSample, Photometric mode & Compression mode
outputSettings.setBitsPerSample(new int[] { 4 });
outputSettings.setCompression(TiffCompressions.AdobeDeflate);
outputSettings.setPhotometric(TiffPhotometrics.Palette);
// Set graycale palette
outputSettings.setPalette(ColorPaletteHelper.create4BitGrayscale(false));
image.save(dataDir + "out_adobedeflate.tiff", outputSettings);
}
// The path to the documents directory.
String dataDir = "dataDir/";
// Load an image through file path location or stream
try (Image image = Image.load(dataDir + "sample.tiff"))
{
// Create an instance of TiffOptions for the resultant image
TiffOptions outputSettings = new TiffOptions(TiffExpectedFormat.Default);
// Set BitsPerSample, Compression, Photometric mode and graycale palette
outputSettings.setBitsPerSample(new int[] { 4 });
outputSettings.setCompression(TiffCompressions.Lzw);
outputSettings.setPhotometric(TiffPhotometrics.Palette);
outputSettings.setPalette(ColorPaletteHelper.create4BitGrayscale(false));
image.save(dataDir + "SampleTiff_out.tiff", outputSettings);
}
// The path to the documents directory.
String dataDir = "dataDir/";
List<String> files = Arrays.asList(dataDir + "TestDemo.tiff", dataDir + "sample.tiff");
TiffOptions createOptions = new TiffOptions(TiffExpectedFormat.Default);
createOptions.setBitsPerSample(new int[] { 1 });
createOptions.setOrientation(TiffOrientations.TopLeft);
createOptions.setPhotometric(TiffPhotometrics.MinIsBlack);
createOptions.setCompression(TiffCompressions.CcittFax3);
createOptions.setFillOrder(TiffFillOrders.Lsb2Msb);
// Create a new image by passing the TiffOptions and size of first frame, we will remove the first frame at the end, cause it will be empty
TiffImage output = null;
List<TiffImage> images = new ArrayList<>();
try
{
for (String file : files)
{
// Create an instance of TiffImage and load the source image
TiffImage input = (TiffImage) Image.load(file);
images.add(input); // Do not dispose before data is fetched. Data is fetched on 'Save' later.
for (TiffFrame frame : input.getFrames())
{
if (output == null)
{
// Create a new tiff image with first frame defined.
output = new TiffImage(TiffFrame.copyFrame(frame));
}
else
{
// Add copied frame to destination image
output.addFrame(TiffFrame.copyFrame(frame));
}
}
}
if (output != null)
{
// Save the result
output.save(Utils.getOutDir() + "ConcatenateTiffImagesHavingSeveralFrames_out.tif", createOptions);
// Release resource
output.close();
}
}
finally
{
// Release resources
for (TiffImage image : images)
{
image.close();
}
}
try (EpsImage image = (EpsImage)Image.load("Sample.eps"))
{
PdfOptions options = new PdfOptions();
PdfCoreOptions coreOptions = new PdfCoreOptions();
coreOptions.setPdfCompliance(PdfComplianceVersion.PdfA1b); // Set required PDF compliance
options.setPdfCoreOptions(coreOptions);
image.setPreviewToExport(EpsPreviewFormat.PostScriptRendering);
image.save(dataDir + "Sample.pdf", options);
}
try (EpsImage image = (EpsImage)Image.load("Sample.eps"))
{
PngOptions options = new PngOptions();
EpsRasterizationOptions epsRasterizationOptions = new EpsRasterizationOptions();
epsRasterizationOptions.setPageWidth(500); // Image width
epsRasterizationOptions.setPageHeight(500); // Image height
options.setVectorRasterizationOptions(epsRasterizationOptions);
image.setPreviewToExport(EpsPreviewFormat.PostScriptRendering); // Render raster image using the PostScript
image.save("Sample.png", options);
}
public void imagingJava1692Test()
{
String inputFilePath = "00020.png";
String outputFilePath = "00020_png.png";
exportImage(inputFilePath, outputFilePath, FileFormat.Png, 0, null);
}
private static void exportImage(
String sourceImageFilePath,
String outputImageFilePath,
long targetFormat,
float rotateAngle,
Integer rotateFlipType)
{
LoadOptions options = new LoadOptions();
options.setBufferSizeHint(450);
RasterImage image = (RasterImage)Image.load(sourceImageFilePath, options);
try
{
if (!image.isCached())
{
// !!! The caching call was in the customer example.
// We strongly recommend that you do not use caching in this case,
// since this leads to a noticeable decrease in performance in this case (in memory optimization strategy).
image.cacheData();
}
if (rotateAngle != 0)
{
image.rotate(rotateAngle);
}
if (rotateFlipType != null)
{
image.rotateFlip(rotateFlipType);
}
int bitsPerPixel = image.getBitsPerPixel();
int bitDepth = bitsPerPixel == 1 ? 1 : bitsPerPixel < 8 ? 8 : 24;
ImageOptionsBase exportOptions;
if (targetFormat == FileFormat.Jpeg)
{
if (bitDepth <= 8)
{
JpegOptions jpegOptions = new JpegOptions();
jpegOptions.setPalette(ColorPaletteHelper.create8BitGrayscale(true));
jpegOptions.setColorType(JpegCompressionColorMode.Grayscale);
exportOptions = jpegOptions;
}
else
{
exportOptions = new JpegOptions();
}
}
else if (targetFormat == FileFormat.Png)
{
PngOptions pngOptions = new PngOptions();
pngOptions.setProgressive(false);
if (bitDepth <= 8)
{
pngOptions.setColorType(PngColorType.Grayscale);
pngOptions.setBitDepth((byte) bitDepth);
}
exportOptions = pngOptions;
}
else if (targetFormat == FileFormat.Tiff)
{
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.Default);
exportOptions = tiffOptions;
switch (bitDepth)
{
case 1:
tiffOptions.setPhotometric(TiffPhotometrics.MinIsWhite);
tiffOptions.setPalette(ColorPaletteHelper.createMonochrome());
tiffOptions.setCompression(TiffCompressions.CcittFax4);
tiffOptions.setBitsPerSample(new int[]{1});
break;
case 8:
tiffOptions.setPhotometric(TiffPhotometrics.MinIsWhite);
tiffOptions.setPalette(ColorPaletteHelper.create8BitGrayscale(true));
tiffOptions.setCompression(TiffCompressions.Deflate);
tiffOptions.setBitsPerSample(new int[]{8});
break;
default:
int bitsPerSample = bitDepth / 3;
tiffOptions.setPhotometric(TiffPhotometrics.Rgb);
tiffOptions.setCompression(TiffCompressions.Jpeg);
tiffOptions.setBitsPerSample(new int[]{bitsPerSample, bitsPerSample, bitsPerSample});
break;
}
}
else
{
return;
}
exportOptions.setBufferSizeHint(2056);
exportOptions.setResolutionSettings(new ResolutionSetting(50, 50));
image.save(outputImageFilePath, exportOptions);
}
finally
{
image.close();
}
}
// List of existing EMF images.
String path = "DataDir/";
String[] files = new String[] { "TestEmfRotatedText.emf", "TestEmfPlusFigures.emf", "TestEmfBezier.emf" };
// Loop for each file name.
for (String file : files)
{
// Input file name & path.
String filePath = path + file;
// Load the EMF image as image and convert it to MetaImage object.
try (com.aspose.imaging.fileformats.emf.MetaImage image = (com.aspose.imaging.fileformats.emf.MetaImage)Image.load(filePath))
{
// Convert the EMF image to WMF image by creating and passing WMF image options class object.
image.save(filePath + "_out.wmf", new com.aspose.imaging.imageoptions.WmfOptions());
}
}
// The path to the documents directory.
String dataDir = "DataDir/";
// Load an existing WMF image
try (Image image = Image.load(dataDir + "input.wmf"))
{
// Create an instance of EmfRasterizationOptions class and set different properties
EmfRasterizationOptions emfRasterizationOptions = new EmfRasterizationOptions();
emfRasterizationOptions.setBackgroundColor(Color.getWhiteSmoke());
emfRasterizationOptions.setPageWidth(image.getWidth());
emfRasterizationOptions.setPageHeight(image.getHeight());
// Create an instance of PdfOptions class and provide rasterization option
PdfOptions pdfOptions = new PdfOptions();
pdfOptions.setVectorRasterizationOptions(emfRasterizationOptions);
// Call the save method, provide output path and PdfOptions to convert the WMF file to PDF and save the output
image.save(dataDir + "ConvertWMFToPDF_out.pdf", pdfOptions);
}
// The path to the documents directory.
String dataDir = "DataDir/";
String inputFileName = dataDir + "thistlegirl_wmfsample.wmf";
String outputFileNamePng = dataDir + "thistlegirl_wmfsample.png";
try (Image image = Image.load(inputFileName))
{
WmfRasterizationOptions rasterizationOptions = new WmfRasterizationOptions();
rasterizationOptions.setBackgroundColor(Color.getWhiteSmoke());
rasterizationOptions.setPageWidth(image.getWidth());
rasterizationOptions.setPageHeight(image.getHeight());
PngOptions imageOptions = new PngOptions();
imageOptions.setVectorRasterizationOptions(rasterizationOptions);
image.save(outputFileNamePng, imageOptions);
}
// The path to the documents directory.
String dataDir = "svg/";
String inputFileName = dataDir + "thistlegirl_wmfsample.wmf";
String outputFileNameSvg = dataDir + "thistlegirl_wmfsample.svg";
try (Image image = Image.load(inputFileName))
{
WmfRasterizationOptions rasterizationOptions = new WmfRasterizationOptions();
rasterizationOptions.setBackgroundColor(Color.getWhiteSmoke());
rasterizationOptions.setPageWidth(image.getWidth());
rasterizationOptions.setPageHeight(image.getHeight());
SvgOptions svgOptions = new SvgOptions();
svgOptions.setVectorRasterizationOptions(rasterizationOptions);
image.save(outputFileNameSvg, svgOptions);
}
// The path to the documents directory.
String dataDir = "DataDir/";
// Load an existing WMF image
try (Image image = Image.load(dataDir + "input.wmf"))
{
// Calculate new Webp image height
double k = (image.getWidth() * 1.00) / image.getHeight();
// Create an instance of EmfRasterizationOptions class and set different properties
EmfRasterizationOptions emfRasterization = new EmfRasterizationOptions();
emfRasterization.setBackgroundColor(Color.getWhiteSmoke());
emfRasterization.setPageWidth(400);
emfRasterization.setPageHeight((int)Math.round(400 / k));
emfRasterization.setBorderX(5);
emfRasterization.setBorderY(10);
// Create an instance of WebPOptions class and provide rasterization option
ImageOptionsBase imageOptions = new WebPOptions();
imageOptions.setVectorRasterizationOptions(emfRasterization);
// Call the save method, provide output path and WebPOptions to convert the WMF file to Webp and save the output
image.save(dataDir + "ConvertWMFToWebp_out.webp", imageOptions);
}
import com.aspose.imaging.Image;
import com.aspose.imaging.RasterImage;
import com.aspose.imaging.fileformats.apng.ApngFrame;
import com.aspose.imaging.fileformats.apng.ApngImage;
import com.aspose.imaging.fileformats.png.PngColorType;
import com.aspose.imaging.imageoptions.ApngOptions;
import com.aspose.imaging.sources.FileCreateSource;
final int AnimationDuration = 1000; // 1 s
final int FrameDuration = 70; // 70 ms
try (RasterImage sourceImage = (RasterImage) Image.load("not_animated.png"))
{
try (ApngOptions createOptions = new ApngOptions())
{
createOptions.setSource(new FileCreateSource("raster_animation.png", false));
createOptions.setDefaultFrameTime(FrameDuration);
createOptions.setColorType(PngColorType.TruecolorWithAlpha);
try (ApngImage apngImage = (ApngImage) Image.create(
createOptions,
sourceImage.getWidth(),
sourceImage.getHeight()))
{
int numOfFrames = AnimationDuration / FrameDuration;
int numOfFrames2 = numOfFrames / 2;
apngImage.removeAllFrames();
// add first frame
apngImage.addFrame(sourceImage, FrameDuration);
// add intermediate frames
for (int frameIndex = 1; frameIndex < numOfFrames - 1; ++frameIndex)
{
apngImage.addFrame(sourceImage, FrameDuration);
ApngFrame lastFrame = (ApngFrame) apngImage.getPages()[apngImage.getPageCount() - 1];
float gamma = frameIndex >= numOfFrames2 ? numOfFrames - frameIndex - 1 : frameIndex;
lastFrame.adjustGamma(gamma);
}
// add last frame
apngImage.addFrame(sourceImage, FrameDuration);
apngImage.save();
}
}
}
import com.aspose.imaging.Color;
import com.aspose.imaging.Image;
import com.aspose.imaging.PointF;
import com.aspose.imaging.fileformats.apng.ApngImage;
import com.aspose.imaging.fileformats.png.PngColorType;
import com.aspose.imaging.imageoptions.ApngOptions;
import com.aspose.imaging.sources.FileCreateSource;
// preparing the animation scene
final int SceneWidth = 400;
final int SceneHeigth = 400;
// Act duration, in milliseconds
final long ActDuration = 1000;
// Total duration, in milliseconds
final long TotalDuration = 4000;
// Frame duration, in milliseconds
final long FrameDuration = 50;
Scene scene = new Scene();
final Ellipse[] ellipse = { new Ellipse() };
ellipse[0].setFillColor(Color.fromArgb(128, 128, 128));
ellipse[0].setCenterPoint(new PointF(SceneWidth / 2f, SceneHeigth / 2f));
ellipse[0].setRadiusX(80);
ellipse[0].setRadiusY(80);
scene.addObject(ellipse[0]);
final Line[] line = { new Line() };
line[0].setColor(Color.getBlue());
line[0].setLineWidth(10);
line[0].setStartPoint(new PointF(30, 30));
line[0].setEndPoint(new PointF(SceneWidth - 30, 30));
scene.addObject(line[0]);
IAnimation lineAnimation1 = new LinearAnimation(new LinearAnimation.AnimationProgressHandler() {
public void invoke(float progress)
{
line[0].setStartPoint(new PointF(30 + (progress * (SceneWidth - 60)), 30 + (progress * (SceneHeigth - 60))));
line[0].setColor(Color.fromArgb((int)((progress * 255)), 0, 255 - (int)((progress * 255))));
}
});
lineAnimation1.setDuration(ActDuration);
IAnimation lineAnimation2 = new LinearAnimation(new LinearAnimation.AnimationProgressHandler() {
public void invoke(float progress)
{
line[0].setEndPoint(new PointF(SceneWidth - 30 - (progress * (SceneWidth - 60)), 30 + (progress * (SceneHeigth - 60))));
line[0].setColor(Color.fromArgb(255, (int)((progress * 255)), 0));
}
});
lineAnimation2.setDuration(ActDuration);
IAnimation lineAnimation3 = new LinearAnimation(new LinearAnimation.AnimationProgressHandler() {
public void invoke(float progress)
{
line[0].setStartPoint(new PointF(SceneWidth - 30 - (progress * (SceneWidth - 60)), SceneHeigth - 30 - (progress * (SceneHeigth - 60))));
line[0].setColor(Color.fromArgb(255 - (int)((progress * 255)), 255, 0));
}
});
lineAnimation3.setDuration(ActDuration);
IAnimation lineAnimation4 = new LinearAnimation(new LinearAnimation.AnimationProgressHandler() {
public void invoke(float progress)
{
line[0].setEndPoint(new PointF(30 + (progress * (SceneWidth - 60)), SceneHeigth - 30 - (progress * (SceneHeigth - 60))));
line[0].setColor(Color.fromArgb(0, 255 - (int)((progress * 255)), (int)((progress * 255))));
}
});
lineAnimation4.setDuration(ActDuration);
SequentialAnimation fullLineAnimation = new SequentialAnimation();
fullLineAnimation.add(lineAnimation1);
fullLineAnimation.add(lineAnimation2);
fullLineAnimation.add(lineAnimation3);
fullLineAnimation.add(lineAnimation4);
IAnimation ellipseAnimation1 = new LinearAnimation(new LinearAnimation.AnimationProgressHandler() {
public void invoke(float progress)
{
ellipse[0].setRadiusX(ellipse[0].getRadiusX() + (progress * 10));
ellipse[0].setRadiusY(ellipse[0].getRadiusY() + (progress * 10));
int compValue = (int)((128 + (progress * 112)));
ellipse[0].setFillColor(Color.fromArgb(compValue, compValue, compValue));
}
});
ellipseAnimation1.setDuration(ActDuration);
IAnimation ellipseAnimation2 = new Delay();
ellipseAnimation2.setDuration(ActDuration);
IAnimation ellipseAnimation3 = new LinearAnimation(new LinearAnimation.AnimationProgressHandler() {
public void invoke(float progress)
{
ellipse[0].setRadiusX(ellipse[0].getRadiusX() - (progress * 10));
int compValue = (int)((240 - (progress * 224)));
ellipse[0].setFillColor(Color.fromArgb(compValue, compValue, compValue));
}
});
ellipseAnimation3.setDuration(ActDuration);
IAnimation ellipseAnimation4 = new LinearAnimation(new LinearAnimation.AnimationProgressHandler() {
public void invoke(float progress)
{
ellipse[0].setRadiusY(ellipse[0].getRadiusY() - (progress * 10));
int compValue = (int)((16 + (progress * 112)));
ellipse[0].setFillColor(Color.fromArgb(compValue, compValue, compValue));
}
});
ellipseAnimation4.setDuration(ActDuration);
SequentialAnimation fullEllipseAnimation = new SequentialAnimation();
fullEllipseAnimation.add(ellipseAnimation1);
fullEllipseAnimation.add(ellipseAnimation2);
fullEllipseAnimation.add(ellipseAnimation3);
fullEllipseAnimation.add(ellipseAnimation4);
ParallelAnimation tmp0 = new ParallelAnimation();
tmp0.add(fullLineAnimation);
tmp0.add(fullEllipseAnimation);
scene.setAnimation(tmp0);
// playing the scene on the newly created ApngImage
ApngOptions createOptions = new ApngOptions();
try
{
createOptions.setSource(new FileCreateSource("vector_animation.png", false));
createOptions.setColorType(PngColorType.TruecolorWithAlpha);
final ApngImage image = (ApngImage) Image.create(createOptions, SceneWidth, SceneHeigth);
try
/*JAVA: was using*/
{
image.setDefaultFrameTime(FrameDuration);
scene.play(image, TotalDuration);
image.save();
}
finally
{
image.close();
}
}
finally
{
createOptions.close();
}
/////////////////////////// Scene.java /////////////////////////////
import com.aspose.imaging.fileformats.apng.ApngFrame;
import com.aspose.imaging.fileformats.apng.ApngImage;
import java.util.ArrayList;
/**
* <p>
* The graphics scene
* </p>
*/
public class Scene
{
/**
* <p>
* The graphics objects
* </p>
*/
private final java.util.List<IGraphicsObject> graphicsObjects = new ArrayList<IGraphicsObject>();
/**
* <p>
* Gets the animation.
* </p>
*/
public final IAnimation getAnimation()
{
return animation;
}
/**
* <p>
* Sets the animation.
* </p>
*/
public final void setAnimation(IAnimation value)
{
animation = value;
}
private IAnimation animation;
/**
* <p>
* Adds the graphics object.
* </p>
*
* @param graphicsObject The graphics object.
*/
public final void addObject(IGraphicsObject graphicsObject)
{
this.graphicsObjects.add(graphicsObject);
}
/**
* <p>
* Plays scene on the specified animation image.
* </p>
*
* @param animationImage The animation image.
* @param totalDuration The total duration.
*/
public final void play(ApngImage animationImage, long totalDuration)
{
/*UInt32*/
long frameDuration = animationImage.getDefaultFrameTime();
/*UInt32*/
long numFrames = (totalDuration / frameDuration);
/*UInt32*/
long totalElapsed = 0;
for (/*UInt32*/long frameIndex = 0; frameIndex < numFrames; frameIndex++)
{
if (this.getAnimation() != null)
{
this.getAnimation().update(totalElapsed);
}
ApngFrame frame = animationImage.getPageCount() == 0 || frameIndex > 0 ? animationImage.addFrame() : (ApngFrame) animationImage.getPages()[0];
com.aspose.imaging.Graphics graphics = new com.aspose.imaging.Graphics(frame);
//foreach to while statements conversion
for (IGraphicsObject graphicsObject : graphicsObjects)
{
graphicsObject.render(graphics);
}
totalElapsed = (totalElapsed + frameDuration);
}
}
}
/////////////////////////// IGraphicsObject.java /////////////////////////////
/**
* <p>
* The graphics object
* </p>
*/
public interface IGraphicsObject
{
/**
* <p>
* Renders this instance using specified graphics.
* </p>
*
* @param graphics The graphics.
*/
void render(com.aspose.imaging.Graphics graphics);
}
/////////////////////////// Line.java /////////////////////////////
import com.aspose.imaging.Color;
import com.aspose.imaging.Pen;
import com.aspose.imaging.PointF;
/**
* <p>
* The line
* </p>
*/
public class Line implements IGraphicsObject
{
/**
* <p>
* Gets the start point.
* </p>
*
* @return the start point.
*/
public final PointF getStartPoint()
{
return startPoint.Clone();
}
/**
* <p>
* Sets the start point.
* </p>
*
*/
public final void setStartPoint(PointF value)
{
startPoint = value.Clone();
}
private PointF startPoint = new PointF();
/**
* <p>
* Gets the end point.
* </p>
*
*/
public final PointF getEndPoint()
{
return endPoint.Clone();
}
/**
* <p>
* Sets the end point.
* </p>
*
*/
public final void setEndPoint(PointF value)
{
endPoint = value.Clone();
}
private PointF endPoint = new PointF();
/**
* <p>
* Gets the width of the line.
* </p>
*
*/
public final float getLineWidth()
{
return lineWidth;
}
/**
* <p>
* Sets the width of the line.
* </p>
*
* @param value the width of the line.
*/
public final void setLineWidth(float value)
{
lineWidth = value;
}
private float lineWidth;
/**
* <p>
* Gets the color.
* </p>
*
* @return the color.
*/
public final Color getColor()
{
return color;
}
/**
* <p>
* Sets the color.
* </p>
*
* @param value the color.
*/
public final void setColor(Color value)
{
color = value.Clone();
}
private Color color = new Color();
/**
* <p>
* Renders this instance using specified graphics.
* </p>
*
* @param graphics The graphics.
*/
public final void render(com.aspose.imaging.Graphics graphics)
{
graphics.drawLine(new Pen(color, lineWidth), startPoint, endPoint);
}
}
/////////////////////////// Ellipse.java /////////////////////////////
import com.aspose.imaging.Color;
import com.aspose.imaging.PointF;
import com.aspose.imaging.brushes.SolidBrush;
/**
* <p>
* The ellipse
* </p>
*/
public class Ellipse implements IGraphicsObject
{
/**
* <p>
* Gets the color of the fill.
* </p>
*
* @return the color of the fill.
*/
public final Color getFillColor()
{
return fillColor.Clone();
}
/**
* <p>
* Sets the color of the fill.
* </p>
*
* @param value the color of the fill.
*/
public final void setFillColor(Color value)
{
fillColor = value.Clone();
}
private Color fillColor = new Color();
/**
* <p>
* Gets the center point.
* </p>
*
* @return the center point.
*/
public final PointF getCenterPoint()
{
return centerPoint.Clone();
}
/**
* <p>
* Sets the center point.
* </p>
*
* @param value the center point.
*/
public final void setCenterPoint(PointF value)
{
centerPoint = value.Clone();
}
private PointF centerPoint = new PointF();
/**
* <p>
* Gets the radius x.
* </p>
*
* @return the radius x.
*/
public final float getRadiusX()
{
return radiusX;
}
/**
* <p>
* Sets the radius x.
* </p>
*
* @param value the radius x.
*/
public final void setRadiusX(float value)
{
radiusX = value;
}
private float radiusX;
/**
* <p>
* Gets the radius y.
* </p>
*
* @return the radius y.
*/
public final float getRadiusY()
{
return radiusY;
}
/**
* <p>
* Sets the radius y.
* </p>
*
* @param value the radius y.
*/
public final void setRadiusY(float value)
{
radiusY = value;
}
private float radiusY;
/**
* <p>
* Renders this instance using specified graphics.
* </p>
*
* @param graphics The graphics.
*/
@Override
public final void render(com.aspose.imaging.Graphics graphics)
{
graphics.fillEllipse(new SolidBrush(fillColor), centerPoint.getX() - radiusX
, centerPoint.getY() - radiusY, radiusX * 2, radiusY * 2);
}
}
/////////////////////////// IAnimation.java /////////////////////////////
/**
* <p>
* The animation
* </p>
*/
public interface IAnimation
{
/**
* <p>
* Gets the duration.
* </p>
*
* @return the duration.
*/
long getDuration();
/**
* <p>
* Sets the duration.
* </p>
*
* @param value the duration.
*/
void setDuration(long value);
/**
* <p>
* Updates the animation progress.
* </p>
*
* @param elapsed The elapsed time, in milliseconds.
*/
void update(long elapsed);
}
/////////////////////////// LinearAnimation.java /////////////////////////////
/**
* <p>
* The linear animation
* </p>
*/
public class LinearAnimation implements IAnimation
{
/**
* <p>
* The progress handler
* </p>
*/
private final AnimationProgressHandler progressHandler;
/**
* <p>
* Animation progress handler delegate
* </p>
*/
public interface AnimationProgressHandler
{
/**
* <p>
* Animation progress handler delegate
* </p>
*
* @param progress The progress, in [0;1] range.
*/
void invoke(float progress);
}
/**
* <p>
* Initializes a new instance of the {@link LinearAnimation} class.
* </p>
*
* @param progressHandler The progress handler.
* @throws NullPointerException progressHandler is null.
*/
public LinearAnimation(AnimationProgressHandler progressHandler)
{
if (progressHandler == null)
{
throw new NullPointerException("progressHandler");
}
this.progressHandler = progressHandler;
}
/**
* <p>
* Gets the duration.
* </p>
*
* @return the duration.
*/
@Override
public final long getDuration()
{
return duration;
}
/**
* <p>
* Sets the duration.
* </p>
*
* @param value the duration.
*/
@Override
public final void setDuration(long value)
{
duration = value;
}
private long duration;
/**
* <p>
* Updates the animation progress.
* </p>
*
* @param elapsed The elapsed time, in milliseconds.
*/
@Override
public final void update(long elapsed)
{
if (elapsed <= duration)
{
this.progressHandler.invoke((float) elapsed / duration);
}
}
}
/////////////////////////// Delay.java /////////////////////////////
/**
* <p>
* The simple delay between other animations
* </p>
*/
public class Delay implements IAnimation
{
/**
* <p>
* Gets the duration.
* </p>
*
* @return the duration.
*/
@Override
public final long getDuration()
{
return duration;
}
/**
* <p>
* Sets the duration.
* </p>
*
* @param value the duration.
*/
@Override
public final void setDuration(long value)
{
duration = value;
}
private long duration;
/**
* <p>
* Updates the animation progress.
* </p>
*
* @param elapsed The elapsed time, in milliseconds.
*/
@Override
public final void update(long elapsed)
{
// Do nothing
}
}
/////////////////////////// ParallelAnimation.java /////////////////////////////
import java.util.ArrayList;
import java.util.Collection;
/**
* <p>
* The parallel animation processor
* </p>
*/
public class ParallelAnimation extends ArrayList<IAnimation> implements IAnimation
{
/**
* <p>
* Initializes a new instance of the {@link ParallelAnimation} class.
* </p>
*/
public ParallelAnimation()
{
// Do nothing
}
/**
* <p>
* Initializes a new instance of the {@link ParallelAnimation} class.
* </p>
*
* @param animations The animations.
*/
public ParallelAnimation(Collection<IAnimation> animations)
{
super(animations);
}
/**
* <p>
* Gets the duration.
* </p>
*
* @return the duration.
*/
@Override
public final long getDuration()
{
long maxDuration = 0;
for (IAnimation animation : this)
{
if (maxDuration < animation.getDuration())
{
maxDuration = animation.getDuration();
}
}
return maxDuration;
}
/**
* <p>
* Sets the duration.
* </p>
*
* @param value the duration.
*/
@Override
public final void setDuration(long value)
{
throw new UnsupportedOperationException();
}
/**
* <p>
* Updates the animation progress.
* </p>
*
* @param elapsed The elapsed time, in milliseconds.
*/
@Override
public final void update(long elapsed)
{
for (IAnimation animation : this)
{
animation.update(elapsed);
}
}
}
/////////////////////////// SequentialAnimation.java /////////////////////////////
import java.util.ArrayList;
import java.util.Collection;
/**
* <p>
* The sequential animation processor
* </p>
*/
public class SequentialAnimation extends ArrayList<IAnimation> implements IAnimation
{
/**
* <p>
* Initializes a new instance of the {@link SequentialAnimation} class.
* </p>
*/
public SequentialAnimation()
{
// Do nothing
}
/**
* <p>
* Initializes a new instance of the {@link SequentialAnimation} class.
* </p>
*
* @param animations The animations.
*/
public SequentialAnimation(Collection<IAnimation> animations)
{
super(animations);
}
/**
* <p>
* Gets the duration.
* </p>
*
* @return the duration.
*/
@Override
public final long getDuration()
{
/*UInt32*/
long summDuration = 0;
for (IAnimation animation : this)
{
summDuration = summDuration + animation.getDuration();
}
return summDuration;
}
/**
* <p>
* Sets the duration.
* </p>
*
* @param value the duration.
*/
@Override
public final void setDuration(long value)
{
throw new UnsupportedOperationException();
}
/**
* <p>
* Updates the animation progress.
* </p>
*
* @param elapsed The elapsed time, in milliseconds.
*/
@Override
public final void update(long elapsed)
{
long totalDuration = 0;
for (IAnimation animation : this)
{
if (totalDuration > elapsed)
{
break;
}
animation.update((elapsed - totalDuration));
totalDuration = totalDuration + animation.getDuration();
}
}
}
// Example 1. Creating an image and setting its pixels.
import com.aspose.imaging.FileFormat;
import com.aspose.imaging.Image;
import com.aspose.imaging.RasterImage;
import com.aspose.imaging.Size;
import com.aspose.imaging.fileformats.apng.ApngImage;
import com.aspose.imaging.fileformats.png.PngColorType;
import com.aspose.imaging.imageoptions.ApngOptions;
import com.aspose.imaging.sources.FileCreateSource;
// Load pixels from source raster image
Size imageSize;
int[] imagePixels;
try (RasterImage sourceImage = (RasterImage) Image.load("not_animated.png"))
{
imageSize = sourceImage.getSize();
imagePixels = sourceImage.loadArgb32Pixels(sourceImage.getBounds());
}
// Create APNG image and set its pixels
try (ApngOptions options = new ApngOptions())
{
options.setSource(new FileCreateSource("created_apng.png", false));
options.setColorType(PngColorType.TruecolorWithAlpha);
try (ApngImage image = (ApngImage)Image.create(options, imageSize.getWidth(), imageSize.getHeight()))
{
image.saveArgb32Pixels(image.getBounds(), imagePixels);
image.save();
}
}
// Check output file format
try (Image image = Image.load("created_apng.png"))
{
assert (image.getFileFormat() == FileFormat.Apng);
assert (image instanceof ApngImage);
}
import com.aspose.imaging.Image;
import com.aspose.imaging.PointF;
import com.aspose.imaging.fileformats.psd.layers.layerresources.vectorpaths.BezierKnotRecord;
import com.aspose.imaging.fileformats.psd.layers.layerresources.vectorpaths.LengthRecord;
import com.aspose.imaging.fileformats.psd.layers.layerresources.vectorpaths.VectorPathRecord;
import com.aspose.imaging.fileformats.tiff.TiffImage;
import com.aspose.imaging.fileformats.tiff.pathresources.PathResource;
static void main()
{
try (TiffImage image = (TiffImage)Image.load("Sample.tif"))
{
LinkedList<PathResource> list = new LinkedList<PathResource>();
PathResource p;
p = new PathResource();
p.setBlockId((short)2000); // Block Id according to Photoshop specification
p.setName("My Clipping Path"); // Path name
p.setRecords(createRecords(0.2f, 0.2f, 0.8f, 0.2f, 0.8f, 0.8f, 0.2f, 0.8f)); // Create path records using coordinates
list.add(p);
p = new PathResource();
p.setBlockId((short)2999); // Block Id according to Photoshop specification
p.setName("My Clipping Path"); // Path name is equal to previous path name
p.setRecords(new ArrayList<VectorPathRecord>()); // No record required
list.add(p);
image.getActiveFrame().setPathResources(list);
image.save("Sample_changed2.tif");
}
}
private static List<VectorPathRecord> createRecords(float ... coordinates)
{
List<VectorPathRecord> records = createBezierRecords(coordinates); // Create Bezier records using coordinates
LengthRecord lr = new LengthRecord();
lr.setOpen(false); // Lets create closed path
lr.setRecordCount(records.size()); // Record count in the path
records.add(0, lr);
return records;
}
private static List<VectorPathRecord> createBezierRecords(float[] coordinates)
{
LinkedList<VectorPathRecord> outList = new LinkedList<VectorPathRecord>();
for (int index = 0; index < coordinates.length; index += 2)
{
PointF point = new PointF(coordinates[index], coordinates[index + 1]);
BezierKnotRecord rec = new BezierKnotRecord();
rec.setPathPoints(new PointF[] { point, point, point });
outList.add(rec);
}
return outList;
}
static void main(String[] args)
{
TiffImage image = (TiffImage)Image.load("Sample.tif");
try
{
final java.util.List<PathResource> list = new LinkedList<PathResource>();
// LengthRecord required by Photoshop specification
final PathResource pathResource = new PathResource();
list.add(pathResource);
// Block Id according to Photoshop specification
pathResource.setBlockId((short)2000);
// Path name
pathResource.setName("My Clipping Path");
// Create path records using coordinates
pathResource.setRecords(createRecords(0.2f, 0.2f, 0.8f, 0.2f, 0.8f, 0.8f, 0.2f, 0.8f));
image.getActiveFrame().setPathResources(list);
image.save("ImageWithPath.tif");
}
finally
{
image.close();
}
}
private static List<VectorPathRecord> createRecords(float ... coordinates)
{
// Create Bezier records using coordinates
java.util.List<VectorPathRecord> records = createBezierRecords(coordinates);
// LengthRecord required by Photoshop specification
LengthRecord lr = new LengthRecord();
// Lets create closed path
lr.setOpen(false);
// Record count in the path
lr.setRecordCount(records.size());
records.add(0, lr);
return records;
}
private static java.util.List<VectorPathRecord> createBezierRecords(float[] coordinates)
{
final java.util.List<VectorPathRecord> list = new LinkedList<VectorPathRecord>();
for (int index = 0; index < coordinates.length - 1; index += 2)
{
PointF point = new PointF(coordinates[index], coordinates[index + 1]);
list.add(createBezierRecord(point));
}
return list;
}
private static VectorPathRecord createBezierRecord(PointF point)
{
BezierKnotRecord it = new BezierKnotRecord();
it.setPathPoints(new PointF[] { point, point, point } );
return it;
}
static void main(String[] args)
{
TiffImage image = (TiffImage)Image.load("Sample.tif");
try
{
final java.util.List<PathResource> list = new LinkedList<PathResource>();
// LengthRecord required by Photoshop specification
final PathResource pathResource = new PathResource();
list.add(pathResource);
// Block Id according to Photoshop specification
pathResource.setBlockId((short)2000);
// Path name
pathResource.setName("My Path");
// Create path records using coordinates
pathResource.setRecords(createRecords(loadPathPoints("d:\\Data\\PathPoints.txt")));
image.getActiveFrame().setPathResources(list);
image.save("ImageWithPath.tif");
}
finally
{
image.close();
}
}
private static List<Float> loadPathPoints(String filePath)
{
List<String> strings = Files.readAllLines(filePath);
List<Float> floats = new ArrayList<Float>(200);
for (String string : strings)
{
String[] its = string.split("[ \t]");
for (String it : its)
{
floats.add(Float.parseFloat(it));
}
}
return floats;
}
private static List<VectorPathRecord> createRecords(List<Float> coordinates)
{
// Create Bezier records using coordinates
java.util.List<VectorPathRecord> records = createBezierRecords(coordinates);
// LengthRecord required by Photoshop specification
LengthRecord lr = new LengthRecord();
// Lets create closed path
lr.setOpen(false);
// Record count in the path
lr.setRecordCount(records.size());
records.add(0, lr);
return records;
}
private static java.util.List<VectorPathRecord> createBezierRecords(List<Float> coordinates)
{
final java.util.List<VectorPathRecord> list = new LinkedList<VectorPathRecord>();
for (int index = 0; index < coordinates.size() - 1; index += 2)
{
PointF point = new PointF(coordinates.get(index), coordinates.get(index + 1));
list.add(createBezierRecord(point));
}
return list;
}
private static VectorPathRecord createBezierRecord(PointF point)
{
BezierKnotRecord it = new BezierKnotRecord();
it.setPathPoints(new PointF[] { point, point, point } );
return it;
}
static void multipageFromVector()
{
// Rasterize vector images
rasterizeSvgToPng("Vector images\\cube.svg", "Vector images\\Rasterized\\cube.png");
rasterizeSvgToPng("Vector images\\greenGrapes.svg", "Vector images\\Rasterized\\greenGrapes.png");
rasterizeSvgToPng("Vector images\\text.svg", "Vector images\\Rasterized\\text.png");
// Load frames
Iterable<RasterImage> frames = loadFrames("Vector images\\Rasterized");
TiffImage image = null;
for (RasterImage frame : frames)
{
if (image == null)
{
// Create TIFF image using the first frame
image = new TiffImage(new TiffFrame(frame));
continue;
}
// Add frames to the TIFF image using the AddPage method
image.addPage(frame);
}
if (image != null)
{
// Save TIFF image using options
TiffOptions options = new TiffOptions(TiffExpectedFormat.TiffJpegRgb);
image.save("MultipageFromVector.tif", options);
}
}
private static void rasterizeSvgToPng(String inputPath, String outputPath)
{
// Load vector image
try (Image image = Image.load(inputPath))
{
// Save PNG image
final PngOptions options = new PngOptions();
// Create rasterization options
final SvgRasterizationOptions svgRasterizationOptions = new SvgRasterizationOptions();
svgRasterizationOptions.setPageWidth(image.getWidth());
svgRasterizationOptions.setPageHeight(image.getHeight());
options.setVectorRasterizationOptions(svgRasterizationOptions);
image.save(outputPath, options);
}
}
static void main(String[] args)
{
// The path to the documents directory.
String dataDir = "Png/";
String outDir = "gif/";
// Load frames
Iterable<RasterImage> frames = loadFrames(dataDir + "Animation frames");
GifImage image = null;
for (RasterImage frame : frames)
{
if (image == null)
{
// Create GIF image using the first frame
image = new GifImage(new GifFrameBlock(frame));
continue;
}
// Add frames to the GIF image using the AddPage method
image.addPage(frame);
}
if (image != null)
{
image.save(outDir + "Multipage.gif");
// Clear all resources
image.close();
}
TiffImage tiffImage = null;
for (RasterImage frame : frames)
{
if (tiffImage == null)
{
// Create TIFF image using the first frame
tiffImage = new TiffImage(new TiffFrame(frame));
continue;
}
// Add frames to the TIFF image using the AddPage method
tiffImage.addPage(frame);
}
if (tiffImage != null)
{
tiffImage.save(outDir + "Multipage.tif", new TiffOptions(TiffExpectedFormat.TiffJpegRgb));
// Clear all resources
tiffImage.close();
}
WebPImage webImage = null;
for (RasterImage frame : frames)
{
if (webImage == null)
{
// Create WEBP image using the first frame
webImage = new WebPImage(frame);
continue;
}
// Add frames to the TIFF image using the AddPage method
webImage.addPage(frame);
}
if (webImage != null)
{
webImage.save(outDir + "Multipage.webp");
// Clear all resources
webImage.close();
}
ApngImage apngImage = null;
for (RasterImage frame : frames)
{
if (apngImage == null)
{
// Create APNG image using the first frame and it's size
apngImage = new ApngImage(new ApngOptions(), frame.getWidth(), frame.getHeight());
}
// Add frames to the APNG image using the AddPage method
apngImage.addPage(frame);
}
if (apngImage != null)
{
apngImage.save(outDir + "Multipage.png");
// Clear all resources
apngImage.close();
}
DicomImage dicomImage = null;
for (RasterImage frame : frames)
{
if (dicomImage == null)
{
// Create DICOM image using the first frame and it's size
dicomImage = new DicomImage(new DicomOptions(), frame.getWidth(), frame.getHeight());
}
// Add frames to the DICOM image using the addPage method
dicomImage.addPage(frame);
}
if (dicomImage != null)
{
// Remove default empty page
dicomImage.removePage(0);
dicomImage.save(outDir + "Multipage.dcm");
// Clear all resources
dicomImage.close();
}
}
private static Iterable<RasterImage> loadFrames(String directory)
{
return new FileList(directory);
}
private static class FileList implements Iterable<RasterImage>
{
private final File[] images;
FileList(String directory)
{
images = new File(directory).listFiles();
}
@Override
public Iterator<RasterImage> iterator()
{
return new Iterator<RasterImage>(){
int index = -1;
@Override
public boolean hasNext()
{
if (images == null || index + 1 >= images.length)
return false;
index++;
return true;
}
@Override
public RasterImage next()
{
return (RasterImage) Image.load(images[index].getAbsolutePath());
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
}
// The path to the documents directory.
String dataDir = "dataDir/";
// Create an instance of TiffOptions and set its various properties
TiffOptions options = new TiffOptions(TiffExpectedFormat.Default);
options.setBitsPerSample(new int[] { 8, 8, 8 });
options.setPhotometric(TiffPhotometrics.Rgb);
options.setXresolution(new TiffRational(72));
options.setYresolution(new TiffRational(72));
options.setResolutionUnit(TiffResolutionUnits.Inch);
options.setPlanarConfiguration(TiffPlanarConfigs.Contiguous);
// Set the Compression to AdobeDeflate
options.setCompression(TiffCompressions.AdobeDeflate);
// Or Deflate
// options.setCompression(TiffCompressions.Deflate);
// Create a new TiffImage with specific size and TiffOptions settings
try (TiffImage tiffImage = new TiffImage(new TiffFrame(options, 100, 100)))
{
// Loop over the pixels to set the color to red
for (int i = 0; i < 100; i++)
{
tiffImage.getActiveFrame().setPixel(i, i, Color.getRed());
}
// Save resultant image
tiffImage.save(dataDir + "CreatingTIFFImageWithCompression.tiff");
}
String dataDir = "dataDir/";
try (SvgImage image = (SvgImage) Image.load(dataDir + "test.svg"))
{
image.crop(new Rectangle(10, 10, 100, 150));
System.out.println(image.getWidth());
System.out.println(image.getHeight());
image.save(dataDir + "test.svg_crop.svg");
}
import com.aspose.imaging.Image;
import com.aspose.imaging.fileformats.dicom.ColorType;
import com.aspose.imaging.imageoptions.DicomOptions;
try (Image inputImage = Image.load("original.jpg"))
{
DicomOptions options = new DicomOptions();
options.setColorType(ColorType.Grayscale8Bit);
inputImage.save("original_8bit.dcm", options);
}
import com.aspose.imaging.Image;
import com.aspose.imaging.fileformats.dicom.ColorType;
import com.aspose.imaging.fileformats.dicom.Compression;
import com.aspose.imaging.fileformats.dicom.CompressionType;
import com.aspose.imaging.imageoptions.DicomOptions;
try (Image inputImage = Image.load("original.jpg"))
{
DicomOptions options = new DicomOptions();
options.setColorType(ColorType.Rgb24Bit);
Compression compression = new Compression();
compression.setType(CompressionType.Jpeg);
options.setCompression(compression);
inputImage.save("original_Jpeg.dcm", options);
}
import com.aspose.imaging.Image;
import com.aspose.imaging.fileformats.dicom.ColorType;
import com.aspose.imaging.fileformats.dicom.Compression;
import com.aspose.imaging.fileformats.dicom.CompressionType;
import com.aspose.imaging.fileformats.jpeg.JpegCompressionMode;
import com.aspose.imaging.fileformats.jpeg.SampleRoundingMode;
import com.aspose.imaging.imageoptions.DicomOptions;
import com.aspose.imaging.imageoptions.JpegOptions;
try (Image inputImage = Image.load("original.jpg"))
{
DicomOptions options = new DicomOptions();
options.setColorType(ColorType.Rgb24Bit);
Compression compression = new Compression();
compression.setType(CompressionType.Jpeg);
// Tuning
JpegOptions jpegOptions = new JpegOptions();
jpegOptions.setCompressionType(JpegCompressionMode.Baseline);
jpegOptions.setSampleRoundingMode(SampleRoundingMode.Truncate);
jpegOptions.setQuality(50);
compression.setJpeg(jpegOptions);
options.setCompression(compression);
inputImage.save("original_Jpeg_2.dcm", options);
}
import com.aspose.imaging.Image;
import com.aspose.imaging.fileformats.dicom.ColorType;
import com.aspose.imaging.fileformats.dicom.Compression;
import com.aspose.imaging.fileformats.dicom.CompressionType;
import com.aspose.imaging.fileformats.jpeg2000.Jpeg2000Codec;
import com.aspose.imaging.imageoptions.DicomOptions;
import com.aspose.imaging.imageoptions.Jpeg2000Options;
try (Image inputImage = Image.load("original.jpg"))
{
DicomOptions options = new DicomOptions();
options.setColorType(ColorType.Rgb24Bit);
Compression compression = new Compression();
compression.setType(CompressionType.Jpeg2000);
// Tuning
Jpeg2000Options jpeg2000Options = new Jpeg2000Options();
jpeg2000Options.setCodec(Jpeg2000Codec.Jp2);
jpeg2000Options.setIrreversible(false);
compression.setJpeg2000(jpeg2000Options);
options.setCompression(compression);
inputImage.save("original_Jpeg2000.dcm", options);
}
// Example 1. Setting a memory limit of 50 megabytes for operations on the created Dicom image
try (DicomOptions imageOptions = new DicomOptions())
{
imageOptions.setSource(new FileCreateSource("created.dcm", false));
imageOptions.setBufferSizeHint(50);
try (Image image = Image.create(imageOptions, 1000, 1000))
{
// Do something with the created image
// ...
image.save();
}
}
// Example 2. Setting a memory limit of 20 megabytes for operations on the loaded Dicom image
LoadOptions loadOptions = new LoadOptions();
loadOptions.setBufferSizeHint(20);
try (Image image = Image.load("image.dcm", loadOptions))
{
// Do something with the loaded image
//...
}
// Example 3. Settings a memory limit of 30 mebagytes for export-to-dicom operation
LoadOptions loadOptions = new LoadOptions();
loadOptions.setBufferSizeHint(30);
try (Image image = Image.load("image.png", loadOptions))
{
image.save("exported.dcm", new DicomOptions());
}
import com.aspose.imaging.Image;
import com.aspose.imaging.fileformats.dicom.ColorType;
import com.aspose.imaging.fileformats.dicom.Compression;
import com.aspose.imaging.fileformats.dicom.CompressionType;
import com.aspose.imaging.imageoptions.DicomOptions;
try (Image inputImage = Image.load("original.jpg"))
{
DicomOptions options = new DicomOptions();
options.setColorType(ColorType.Rgb24Bit);
Compression compression = new Compression();
compression.setType(CompressionType.None);
options.setCompression(compression);
inputImage.save("original_Uncompressed.dcm", options);
}
import com.aspose.imaging.Image;
import com.aspose.imaging.fileformats.dicom.ColorType;
import com.aspose.imaging.fileformats.dicom.Compression;
import com.aspose.imaging.fileformats.dicom.CompressionType;
import com.aspose.imaging.imageoptions.DicomOptions;
try (Image inputImage = Image.load("original.jpg"))
{
DicomOptions options = new DicomOptions();
options.setColorType(ColorType.Rgb24Bit);
Compression compression = new Compression();
compression.setType(CompressionType.Rle);
options.setCompression(compression);
inputImage.save("original_Rle.dcm", options);
}
import com.aspose.imaging.Image;
import com.aspose.imaging.imageoptions.PngOptions;
try (com.aspose.imaging.fileformats.dicom.DicomImage image =
(com.aspose.imaging.fileformats.dicom.DicomImage ) Image.load("input.dicom"))
{
PngOptions options = new PngOptions();
image.save("output.png", options);
}
String file = "example.emf";
String baseFolder = "D:\\Compressed\\";
String inputFile = baseFolder + file;
String outFile = inputFile + ".emz";
try (final Image image = Image.load(inputFile))
{
image.save(outFile, new EmfOptions(){{ setCompress(true); }});
}
String file = "example.emz";
String baseFolder = "D:\\Compressed\\";
String inputFile = baseFolder + file;
String outFile = inputFile + ".emf";
try (final Image image = Image.load(inputFile))
{
image.save(outFile, new EmfOptions(){{ setCompress(false); }});
}
import com.aspose.imaging.Image;
import com.aspose.imaging.imageoptions.PsdOptions;
try (com.aspose.imaging.fileformats.eps.EpsImage image = (com.aspose.imaging.fileformats.eps.EpsImage)Image.load("Rings.eps"))
{
PsdOptions options = new PsdOptions();
image.save(@"Rings.psd", options);
}
// The path to the documents directory.
String dataDir = "D:/DataDir/";
// Load an image in an instance of Image and Setting for image data to be cashed
try (RasterImage rasterImage = (RasterImage)Image.load(dataDir + "aspose-logo.jpg"))
{
rasterImage.cacheData();
// Create an instance of Rectangle class and define X,Y and Width, height of the rectangle, and Save output image
Rectangle destRect = new Rectangle(-200, -200, 300, 300);
rasterImage.save(dataDir + "Grayscaling_out.jpg", new JpegOptions(), destRect);
}
import com.aspose.imaging.Image;
import com.aspose.imaging.fileformats.apng.ApngImage;
import com.aspose.imaging.imageoptions.GifOptions;
try (Image image = Image.load("elephant.png"))
{
// Checking the type of loaded image
assert (image instanceof ApngImage);
// Save to the same format
image.save("elephant_same_format.png");
// Export to the other animated format
image.save("elephant.png.gif", new GifOptions());
}
try (Image image = Image.load("Sample.cdr"))
{
Html5CanvasOptions html5CanvasOptions = new Html5CanvasOptions();
CdrRasterizationOptions cdrOptions = new CdrRasterizationOptions();
cdrOptions.setPageWidth(image.getWidth());
cdrOptions.setPageHeight(image.getHeight());
html5CanvasOptions.setVectorRasterizationOptions(cdrOptions);
image.save("Canvas.html", html5CanvasOptions);
}
//Example of export from eps to Dxf.
String inputFileName = "Pooh group.eps";
String outputFilePath = "result.dxf";
try (Image image = Image.load(inputFilePath))
{
DxfOptions options = new DxfOptions();
options.setTextAsLines(true);
options.setConvertTextBeziers(true);
options.setBezierPointCount((byte) 20);
image.save(outputFilePath, options);
}
String baseDirectoryPath = "D:\\";
String fileName = "Animation.gif";
String inputFilePath = baseDirectoryPath + fileName;
String outputFilePath = inputFilePath + "_FullFrame.pdf";
try (Image image = Image.load(inputFilePath))
{
PdfOptions pdfOptions = new PdfOptions();
pdfOptions.setMultiPageOptions(new MultiPageOptions(new IntRange(2, 5)));
pdfOptions.setFullFrame(true);
image.save(outputFilePath, pdfOptions);
}
String baseDirectoryPath = "D:\\";
String fileName = "Animation.gif";
String inputFilePath = baseDirectoryPath + fileName;
String outputFilePath = inputFilePath + "_FullFrame.tif";
String outputFilePath1 = inputFilePath + "_NonFullFrame.tif";
try (Image image = Image.load(inputFilePath))
{
MultiPageOptions multiPageOptions = new MultiPageOptions(new IntRange(2, 5));
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.TiffDeflateRgb);
tiffOptions.setMultiPageOptions(multiPageOptions);
tiffOptions.setFullFrame(true);
image.save(outputFilePath, tiffOptions);
tiffOptions.setFullFrame(false);
image.save(outputFilePath1, tiffOptions);
}
try (Image image = Image.load("Sample.svg"))
{
Html5CanvasOptions html5CanvasOptions = new Html5CanvasOptions();
html5CanvasOptions.setVectorRasterizationOptions(new SvgRasterizationOptions());
image.save("Canvas.html", html5CanvasOptions);
}
//Load an existing image (of type Gif) in an instance of Image class
com.aspose.imaging.Image image = com.aspose.imaging.Image.load(dataDir + "sample.gif");
try
{
//Export to BMP file format using the default options
image.save(dataDir + "ExportImageToDifferentFormats_out.bmp" , new com.aspose.imaging.imageoptions.BmpOptions());
//Export to JPEG file format using the default options
image.save(dataDir + "ExportImageToDifferentFormats_out.jpeg", new com.aspose.imaging.imageoptions.JpegOptions());
//Export to PNG file format using the default options
image.save(dataDir + "ExportImageToDifferentFormats_out.png", new com.aspose.imaging.imageoptions.PngOptions());
//Export to TIFF file format using the default options
image.save(dataDir + "ExportImageToDifferentFormats_out.tiff", new TiffOptions(TiffExpectedFormat.Default));
}
finally
{
image.close();
}
// The path to the documents directory.
String dataDir = "DataDir/";
try (TiffImage multiImage = (TiffImage) Image.load(dataDir + "sample.tiff"))
{
// Create an instance of int to keep track of frames in TiffImage
int frameCounter = 0;
// Iterate over the TiffFrames in TiffImage
for (TiffFrame tiffFrame : multiImage.getFrames())
{
multiImage.setActiveFrame(tiffFrame);
// Load Pixels of TiffFrame into an array of Colors
Color[] pixels = multiImage.loadPixels(tiffFrame.getBounds());
// Create an instance of bmpCreateOptions
try (BmpOptions bmpCreateOptions = new BmpOptions())
{
bmpCreateOptions.setBitsPerPixel(24);
// Set the Source of bmpCreateOptions as FileCreateSource by specifying the location where output will be saved
bmpCreateOptions.setSource(new FileCreateSource(String.format("%sConcatExtractTIFFFramesToBMP_out%d.bmp", dataDir, frameCounter), false));
// Create a new bmpImage
try (BmpImage bmpImage = (BmpImage) Image.create(bmpCreateOptions, tiffFrame.getWidth(), tiffFrame.getHeight()))
{
// Save the bmpImage with pixels from TiffFrame
bmpImage.savePixels(tiffFrame.getBounds(), pixels);
bmpImage.save();
}
}
frameCounter++;
}
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
TiffImage multiImage = (TiffImage) Image.load(dataDir + "sample.tif");
int frameCounter = 0;
for (TiffFrame tiffFrame : multiImage.getFrames()) {
multiImage.setActiveFrame(tiffFrame);
Color[] pixels = multiImage.loadPixels(tiffFrame.getBounds());
JpegOptions jpgCreateOptions = new JpegOptions();
jpgCreateOptions
.setSource(new FileCreateSource(String.format(dataDir + "Concat" + frameCounter + ".jpg"), false));
JpegImage jpgImage = (JpegImage) Image.create(jpgCreateOptions, tiffFrame.getWidth(),
tiffFrame.getHeight());
{
jpgImage.savePixels(tiffFrame.getBounds(), pixels);
jpgImage.save();
}
frameCounter++;
}
import com.aspose.imaging.Image;
import com.aspose.imaging.fileformats.tiff.TiffImage;
import com.aspose.imaging.fileformats.tiff.pathresources.PathResource;
import java.util.List;
import java.util.Optional;
try (TiffImage image = (TiffImage)Image.load("Sample.tif"))
{
// Get path resources from TIFF image
List<PathResource> pathResources = image.getActiveFrame().getPathResources();
// Determine clipping path name
Optional<PathResource> first = pathResources.stream().filter(it -> it.getBlockId() == 2999).findFirst();
if (first.isPresent())
{
String clippingPathName = first.get().getName();
// Get clipping path
PathResource clippingPath = pathResources.stream().filter(x -> x.getName().equals(clippingPathName)).findFirst().get();
// Write record count to the console
System.out.print("Clipping path record count: ");
System.out.println(clippingPath.getRecords().size());
}
}
// To improve masking results, data of the specific objects that should be included in the foreground masking result could be provided.
List<AssumedObjectData> assumedObjects = new ArrayList<AssumedObjectData>(2);
// THe object type and the area containing that object should be specified.
assumedObjects.add(new AssumedObjectData(DetectedObjectType.Human, new Rectangle(100, 100, 150, 300)));
assumedObjects.add(new AssumedObjectData(DetectedObjectType.Dog, new Rectangle(300, 100, 50, 30)));
MaskingResult[] results;
try (RasterImage image = (RasterImage)Image.load("input.jpg"))
{
// To use Graph Cut with auto calculated strokes, AutoMaskingGraphCutOptions is used.
AutoMaskingGraphCutOptions options = new AutoMaskingGraphCutOptions();
options.setAssumedObjects(assumedObjects);
// Indicating that a new calculation of the default strokes should be performed during the image decomposition.
options.setCalculateDefaultStrokes(true);
// Setting post-process feathering radius based on the image size.
options.setFeatheringRadius((Math.max(image.getWidth(), image.getHeight()) / 500) + 1);
options.setMethod(SegmentationMethod.GraphCut);
options.setDecompose(false);
options.setBackgroundReplacementColor(Color.getTransparent());
final PngOptions pngOptions = new PngOptions();
pngOptions.setColorType(PngColorType.TruecolorWithAlpha);
pngOptions.setSource(new FileCreateSource("tempFile"));
options.setExportOptions(pngOptions);
results = new ImageMasking(image).decompose(options);
}
// Saving final masking result.
try (RasterImage resultImage = (RasterImage)results[1].getImage())
{
final PngOptions pngOptions = new PngOptions();
pngOptions.setColorType(PngColorType.TruecolorWithAlpha);
resultImage.save("output.png", pngOptions);
}
// Release resources
for (MaskingResult result : results)
{
result.close();
}
MaskingResult[] results;
try (RasterImage image = (RasterImage)Image.load("input.jpg"))
{
// To use Graph Cut with auto calculated strokes, AutoMaskingGraphCutOptions is used.
AutoMaskingGraphCutOptions options = new AutoMaskingGraphCutOptions();
// Indicating that a new calculation of the default strokes should be performed during the image decomposition.
options.setCalculateDefaultStrokes(true);
// Setting post-process feathering radius based on the image size.
options.setFeatheringRadius((Math.max(image.getWidth(), image.getHeight()) / 500) + 1);
options.setMethod(SegmentationMethod.GraphCut);
options.setDecompose(false);
options.setBackgroundReplacementColor(Color.getTransparent());
final PngOptions exportOptions = new PngOptions();
exportOptions.setColorType(PngColorType.TruecolorWithAlpha);
exportOptions.setSource(new FileCreateSource("tempFile"));
options.setExportOptions(exportOptions);
results = new ImageMasking(image).decompose(options);
}
try (RasterImage resultImage = (RasterImage)results[1].getImage())
{
final PngOptions exportOptions = new PngOptions();
exportOptions.setColorType(PngColorType.TruecolorWithAlpha);
resultImage.save("output.png", exportOptions);
}
// Release resources
for (MaskingResult result : results)
{
result.close();
}
// To improve masking results, data of the specific objects that should be included in the foreground masking result could be provided.
List<AssumedObjectData> assumedObjects = new ArrayList<AssumedObjectData>(2);
// THe object type and the area containing that object should be specified.
assumedObjects.add(new AssumedObjectData(DetectedObjectType.Human, new Rectangle(100, 100, 150, 300)));
assumedObjects.add(new AssumedObjectData(DetectedObjectType.Dog, new Rectangle(300, 100, 50, 30)));
MaskingResult[] results;
AutoMaskingGraphCutOptions options;
// First masking iteration is performed to get auto calculated foreground/background brushstrokes.
try (RasterImage image = (RasterImage)Image.load("input.jpg"))
{
// To use Graph Cut with auto calculated strokes, AutoMaskingGraphCutOptions is used.
options = new AutoMaskingGraphCutOptions();
options.setAssumedObjects(assumedObjects);
// Indicating that a new calculation of the default strokes should be performed during the image decomposition.
options.setCalculateDefaultStrokes(true);
// Setting post-process feathering radius.
options.setFeatheringRadius(3);
options.setMethod(SegmentationMethod.GraphCut);
options.setDecompose(false);
options.setBackgroundReplacementColor(Color.getTransparent());
final PngOptions pngOptions = new PngOptions();
pngOptions.setColorType(PngColorType.TruecolorWithAlpha);
pngOptions.setSource(new FileCreateSource("tempFile"));
options.setExportOptions(pngOptions);
results = new ImageMasking(image).decompose(options);
}
// At this point applied foreground/background strokes can be analyzed and based on it additional
// foreground/background strokes can be manually provided.
Point[] appliedBackgroundStrokes = options.getDefaultBackgroundStrokes();
Point[] appliedForegroundStrokes = options.getDefaultForegroundStrokes();
Rectangle[] appliedObjectRectangles = options.getDefaultObjectsRectangles();
try (RasterImage resultImage = (RasterImage)results[1].getImage())
{
final PngOptions pngOptions = new PngOptions();
pngOptions.setColorType(PngColorType.TruecolorWithAlpha);
resultImage.save("output.png", pngOptions);
}
// Second masking iteration is performed to further improve masking quality by adding new manually chosen foreground/background points.
try (RasterImage image = (RasterImage)Image.load("input.jpg"))
{
// Re-using AutoMaskingGraphCutOptions there is no need to perform default stroke calculations a second time.
options.setCalculateDefaultStrokes(false);
// When both default strokes and ObjectsPoints in the Args property of AutoMaskingArgs are provided, Point arrays are end up combined.
// The first ObjectsPoints array is considered to be a background points array and
// the second ObjectsPoints array is considered to be a foreground points array.
// When both DefaultObjectsRectangles and ObjectsRectangles in the Args property of AutoMaskingArgs are provided,
// only the array from the Args is being used.
final AutoMaskingArgs maskingArgs = new AutoMaskingArgs();
maskingArgs.setObjectsPoints(new Point[][]
{
new Point[] { new Point(100, 100), new Point(150, 100) },
new Point[] { new Point(500, 200) },
});
maskingArgs.setObjectsRectangles(new Rectangle[]
{
new Rectangle(100, 100, 300, 300),
});
options.setArgs(maskingArgs);
results = new ImageMasking(image).decompose(options);
}
// Saving final masking result.
try (RasterImage resultImage = (RasterImage)results[1].getImage())
{
final PngOptions pngOptions = new PngOptions();
pngOptions.setColorType(PngColorType.TruecolorWithAlpha);
resultImage.save("output.png", pngOptions);
}
// Release resources
for (MaskingResult result : results)
{
result.close();
}
MaskingResult[] results;
try (RasterImage image = (RasterImage) Image.load("input.jpg"))
{
// To apply feathering, GraphCutMaskingOptions is used.
GraphCutMaskingOptions options = new GraphCutMaskingOptions();
// Setting post-process feathering radius.
options.setFeatheringRadius(3);
options.setMethod(SegmentationMethod.GraphCut);
options.setDecompose(false);
options.setBackgroundReplacementColor(Color.getTransparent());
final PngOptions pngOptions = new PngOptions();
pngOptions.setColorType(PngColorType.TruecolorWithAlpha);
pngOptions.setSource(new FileCreateSource("tempFile"));
options.setExportOptions(pngOptions);
// Foreground/background strokes are passed to the
// AutoMaskingArgs Args property's ObjectsPoints array.
final AutoMaskingArgs maskingArgs = new AutoMaskingArgs();
maskingArgs.setObjectsPoints(new Point[][]
{
new Point[]
{
new Point(100, 100),
},
});
options.setArgs(maskingArgs);
results = new ImageMasking(image).decompose(options);
}
// Saving final masking result.
try (RasterImage resultImage = (RasterImage) results[1].getImage())
{
final PngOptions pngOptions = new PngOptions();
pngOptions.setColorType(PngColorType.TruecolorWithAlpha);
resultImage.save("output.png", pngOptions);
}
// Release resources
for (MaskingResult result : results)
{
result.close();
}
import com.aspose.imaging.Image;
import com.aspose.imaging.Graphics;
try (Image backgoundImage = Image.load("image1.png"))
{
Graphics gr = new Graphics(backgoundImage);
com.aspose.imaging.StringFormat format = new com.aspose.imaging.StringFormat();
com.aspose.imaging.SizeF size = gr.measureString("Test", new com.aspose.imaging.Font("Arial",10), com.aspose.imaging.SizeF.getEmpty(), format);
System.out.println("Size.Width = " + size.getWidth()); // Should be 31.15668f +/- 1.0f
System.out.println("Size.Height = " + size.getHeight()); // Should be 16.5625f +/- 1.0f
}
//Please create folder - "fonts" in project, and add in this folder required fonts.
//And execute this code:
String currentFolder = "."; // here you can set full path to your fonts folder.
FontSettings.setFontsFolder(currentFolder + "fonts");
FontSettings.setGetSystemAlternativeFont(false);
exportToPng("missing-font2.odg", "Arial", "arial.png");
exportToPng("missing-font2.odg", "Courier New", "courier.png");
private static void exportToPng(String filePath, String defaultFontName, String outfileName)
{
FontSettings.setDefaultFontName(defaultFontName);
try (com.aspose.imaging.Image document = com.aspose.imaging.Load(filePath))
{
PngOptions saveOptions = new PngOptions();
OdgRasterizationOptions vectorOptions = new OdgRasterizationOptions();
vectorOptions.setPageWidth(1000);
vectorOptions.setPageHeight(1000);
saveOptions.setVectorRasterizationOptions(vectorOptions);
document.save(outfileName, saveOptions);
}
}
// The path to the documents directory.
String dataDir = "dataDir/jpeg/";
// Load an existing image into an instance of RasterImage class
try (RasterImage rasterImage = (RasterImage)Image.load(dataDir + "aspose-logo.jpg"))
{
if (!rasterImage.isCached())
{
rasterImage.cacheData();
}
// Create an instance of Rectangle class with desired size, Perform the crop operation on object of Rectangle class and Save the results to disk
Rectangle rectangle = new Rectangle(20, 20, 20, 20);
rasterImage.crop(rectangle);
rasterImage.save(dataDir + "CroppingByRectangle_out.jpg");
}
// The path to the documents directory.
String dataDir = "dataDir/jpeg/";
// Load an existing image into an instance of RasterImage class
try (RasterImage rasterImage = (RasterImage)Image.load(dataDir + "aspose-logo.jpg"))
{
// Before cropping, the image should be cached for better performance
if (!rasterImage.isCached())
{
rasterImage.cacheData();
}
// Define shift values for all four sides
int leftShift = 10;
int rightShift = 10;
int topShift = 10;
int bottomShift = 10;
// Based on the shift values, apply the cropping on image Crop method will shift the image bounds toward the center of image and Save the results to disk
rasterImage.crop(leftShift, rightShift, topShift, bottomShift);
rasterImage.save(dataDir + "CroppingByShifts_out.jpg");
}
try (Image image = Image.load("test.jpg"))
{
image.save("test.tga", new TgaOptions());
}
try (TiffImage image = (TiffImage)Image.load("Sample.tif"))
{
List<PathResource> paths = image.getActiveFrame().getPathResources();
image.getActiveFrame().setPathResources(paths.subList(0, 1));
image.save();
}
try (RasterImage image = (RasterImage)Image.load("test.png"))
{
try (TgaImage tgaImage = new TgaImage(image))
{
tgaImage.save("test.tga");
}
}
try (WebPImage image = (WebPImage)Image.load(inputFile))
{
image.resize(300, 450, ResizeType.HighQualityResample);
WebPOptions options = new WebPOptions();
options.setQuality(50);
options.setLossless(false);
image.save("output.webp", options);
}
String dataDir = "/anyDir/";
String sourceFilePath = "testTileDeflate.tif";
String outputFilePath = "testTileDeflate Cmyk Icc.tif";
TiffOptions options = new TiffOptions(TiffExpectedFormat.TiffLzwCmyk);
try (Image image = Image.load(sourceFilePath))
{
image.save(outputFilePath, options);
}
// Example 4. Exporting to APNG file format from other non-animated format
import com.aspose.imaging.Image;
import com.aspose.imaging.imageoptions.ApngOptions;
try (Image image = Image.load("img4.tif"))
{
// Setting up the default frame duration
ApngOptions options = new ApngOptions();
options.setDefaultFrameTime(500); // 500 ms
image.save("img4.tif.500ms.png", options);
options.setDefaultFrameTime(250); // 250 ms
image.save("img4.tif.250ms.png", options);
}
// Example 3. Exporting to APNG file format from other animated format
import com.aspose.imaging.Image;
import com.aspose.imaging.imageoptions.ApngOptions;
try (Image image = Image.load("Animation1.webp"))
{
// Export to APNG animation with unlimited animation cycles as default
image.save("Animation1.webp.png", new ApngOptions());
// Setting up animation cycles
ApngOptions options = new ApngOptions();
options.setNumPlays(5); // 5 cycles
image.save("Animation2.webp.png", options);
}
try (TgaImage image = (TgaImage) Image.load("test.tga"))
{
image.setDateTimeStamp(new Date());
image.setAuthorName("John Smith");
image.setAuthorComments("Comment");
image.setImageId("ImageId");
image.setJobNameOrId("Important Job");
image.setJobTime(new Date(0, Calendar.JANUARY, 10));
image.setTransparentColor(Color.fromArgb(123));
image.setSoftwareId("SoftwareId");
image.setSoftwareVersion("abc1");
image.setSoftwareVersionLetter('a');
image.setSoftwareVersionNumber(2);
image.setXOrigin(1000);
image.setYOrigin(1000);
image.save("test.tga");
}
// The path to the documents directory.
String dataDir = "dataDir/";
// Create an instance of TiffImage and load the file from disc
try (TiffImage multiImage = (TiffImage) Image.load(dataDir + "SampleTiff1.tiff"))
{
// Initialize a variable to keep track of the frames in the image
int i = 0;
// Iterate over the tiff frame collection and Save the frame directly on disc in PNG format
for (TiffFrame tiffFrame : multiImage.getFrames())
{
tiffFrame.save(dataDir + i + "_out.png", new PngOptions());
}
}
// The path to the documents directory.
String dataDir = "dataDir/";
// Create an instance of TiffOptions and set its various properties
TiffOptions options = new TiffOptions(TiffExpectedFormat.Default);
options.setBitsPerSample(new int[] { 8, 8, 8 });
options.setPhotometric(TiffPhotometrics.Rgb);
options.setXresolution(new TiffRational(72));
options.setYresolution(new TiffRational(72));
options.setResolutionUnit(TiffResolutionUnits.Inch);
options.setPlanarConfiguration(TiffPlanarConfigs.Contiguous);
// Set the Compression to AdobeDeflate
options.setCompression(TiffCompressions.AdobeDeflate);
// Or Deflate
// options.setCompression(TiffCompressions.Deflate);
// Load an existing image in an instance of RasterImage
try (RasterImage image = (RasterImage) Image.load(dataDir + "SampleTiff1.tiff"))
{
// Create a new TiffImage from the RasterImage and Save the resultant image while passing the instance of TiffOptions
try (TiffImage tiffImage = new TiffImage(new TiffFrame(image)))
{
tiffImage.save(dataDir + "SavingRasterImage_out.tiff", options);
}
}
String baseFolder = "D:\\";
String fileName = "AFREY-Original.tif";
String inputFileName = baseFolder + fileName;
String outFileName = inputFileName + ".pdf";
try (TiffImage tiffImage = (TiffImage)Image.load(inputFileName))
{
PdfOptions pdfOptions = new PdfOptions();
pdfOptions.setResolutionSettings(new ResolutionSetting(tiffImage.getHorizontalResolution(), tiffImage.getVerticalResolution()));
tiffImage.save(outFileName, pdfOptions);
}
// The path to the documents directory.
String dataDir = "dataDir/";
// Create an instance of TiffImage and load the file from disc
try (TiffImage multiImage = (TiffImage)Image.load(dataDir + "SampleTiff1.tiff"))
{
// Initialize a variable to keep track of the frames in the image, Iterate over the tiff frame collection and Save the image
int i = 0;
for (TiffFrame tiffFrame : multiImage.getFrames())
{
tiffFrame.save(dataDir + i + "_out.tiff", new TiffOptions(TiffExpectedFormat.TiffJpegRgb));
}
}
// The path to the documents directory.
String baseFolder = Utils.getSharedDataDir(SupportOfCDR.class) + "CDR/";
String inputFileName = baseFolder + "test.cdr";
long expectedFileFormat = FileFormat.Cdr;
long realFileFormat = Image.getFileFormat(inputFileName);
Assert.assertEquals(expectedFileFormat, realFileFormat, "File format is incorrect!");
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(CMXToPNGConversion.class) + "CMX/";
// Example of exporting the entire document page
String[] fileNames = new String[] {
"Rectangle.cmx",
"Rectangle+Fill.cmx",
"Ellipse.cmx",
"Ellipse+fill.cmx",
"brushes.cmx",
"outlines.cmx",
"order.cmx",
"many_images.cmx",
};
for (String fileName: fileNames) {
Image image = Image.load(dataDir + fileName);
try {
CmxRasterizationOptions cmxRasterizationOptions = new CmxRasterizationOptions();
cmxRasterizationOptions.setPositioning(PositioningTypes.DefinedByDocument);
cmxRasterizationOptions.setSmoothingMode(SmoothingMode.AntiAlias);
PngOptions options = new PngOptions();
options.setVectorRasterizationOptions(cmxRasterizationOptions);
image.save(dataDir + fileName + ".docpage.png", options);
} finally {
image.close();
}
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
TiffImage image = (TiffImage) com.aspose.imaging.Image.load(dataDir + "sample.tif");
image.alignResolutions();
// Save the results to output path.
image.save(dataDir + "AligHorizontalAndVeticalResolutions_out.tiff");
int framesCount = image.getFrames().length;
for (int i = 0; i < framesCount; i++) {
TiffFrame frame = image.getFrames()[i];
// All resolutions after aligment must be equal
System.out.println("Horizontal and vertical resolutions are equal:"
+ ((int) frame.getVerticalResolution() == (int) frame.getHorizontalResolution()));
}
// 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");
// Convert the image into RasterImage.
RasterImage rasterImage = (RasterImage) image;
if (rasterImage == null) {
return;
}
// Get Bounds[rectangle] of image.
com.aspose.imaging.Rectangle rect = image.getBounds();
// Create an instance of BilateralSmoothingFilterOptions class with size
// parameter.
com.aspose.imaging.imagefilters.filteroptions.BilateralSmoothingFilterOptions bilateralOptions = new com.aspose.imaging.imagefilters.filteroptions.BilateralSmoothingFilterOptions(
3);
// Create an instance of SharpenFilterOptions class.
com.aspose.imaging.imagefilters.filteroptions.SharpenFilterOptions sharpenOptions = new com.aspose.imaging.imagefilters.filteroptions.SharpenFilterOptions();
// Supply the filters to raster image.
rasterImage.filter(rect, bilateralOptions);
rasterImage.filter(rect, sharpenOptions);
// Adjust the contrast accordingly.
rasterImage.adjustContrast(-10);
// Set brightness using Binarize Bradley
rasterImage.binarizeBradley(80);
// Save the results to output path.
rasterImage.save(dataDir + "a1_out.jpg");
// 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.gif");
// caste the image into RasterImage
RasterImage rasterImage = (RasterImage) image;
if (rasterImage == null) {
return;
}
// Create an instance of GaussWienerFilterOptions class and set the
// radius size and smooth value.
GaussWienerFilterOptions options = new GaussWienerFilterOptions(12, 3);
options.setGrayscale(true);
// apply MedianFilterOptions filter to RasterImage object.
rasterImage.filter(image.getBounds(), options);
// Save the resultant image
image.save(dataDir + "ApplyGaussWienerFilter_out.gif");
// 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.gif");
// caste the image into RasterImage
RasterImage rasterImage = (RasterImage) image;
if (rasterImage == null) {
return;
}
// Create an instance of GaussWienerFilterOptions class and set the
// radius size and smooth value.
GaussWienerFilterOptions options = new GaussWienerFilterOptions(5, 1.5);
options.setBrightness(1);
// apply MedianFilterOptions filter to RasterImage object.
rasterImage.filter(image.getBounds(), options);
// Save the resultant image
image.save(dataDir + "ApplyGaussWienerFilter_out.gif");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load the noisy image
Image image = Image.load(dataDir + "aspose-logo.gif");
// caste the image into RasterImage
RasterImage rasterImage = (RasterImage) image;
if (rasterImage == null)
{
return;
}
// Create an instance of MedianFilterOptions class and set the size.
MedianFilterOptions options = new MedianFilterOptions(4);
// Apply MedianFilterOptions filter to RasterImage object.
rasterImage.filter(image.getBounds(), options);
// Save the resultant image
image.save(dataDir + "median_test_denoise_out.gif");
// 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.gif");
// caste the image into RasterImage
RasterImage rasterImage = (RasterImage) image;
if (rasterImage == null) {
return;
}
// Create an instance of MotionWienerFilterOptions class and set the
// length, smooth value and angle.
MotionWienerFilterOptions options = new MotionWienerFilterOptions(50, 9, 90);
options.setGrayscale(true);
// apply MedianFilterOptions filter to RasterImage object.
rasterImage.filter(image.getBounds(), options);
// Save the resultant image
image.save(dataDir + "ApplyingMotionWienerFilter_out.gif");
// Load an image in an instance of Image
try (Image image = Image.load(dataDir + "aspose-logo.jpg"))
{
// Cast the image to RasterCachedImage and Check if image is cached
RasterCachedImage rasterCachedImage = (RasterCachedImage)image;
if (!rasterCachedImage.IsCached)
{
// Cache image if not already cached
rasterCachedImage.CacheData();
}
// Binarize image with predefined fixed threshold and Save the resultant image
rasterCachedImage.binarizeFixed((byte) 100);
rasterCachedImage.save(dataDir + "BinarizationWithFixedThreshold_out.jpg");
}
// Load an image in an instance of Image
try (Image image = Image.load(dataDir + "aspose-logo.jpg"))
{
// Cast the image to RasterCachedImage and Check if image is cached
RasterCachedImage rasterCachedImage = (RasterCachedImage) image;
if (!rasterCachedImage.isCached())
{
// Cache image if not already cached
rasterCachedImage.cacheData();
}
// Binarize image with Otsu Thresholding
rasterCachedImage.binarizeOtsu();
// Save the resultant image
rasterCachedImage.save(dataDir + "BinarizationWithOtsuThreshold_out.jpg");
}
String dataDir = Utils.getSharedDataDir(BMPToPDF.class) + "ConvertingImages/";
String outputFile = "result.pdf";
BmpImage image = (BmpImage)Image.load(dataDir + "somefile.bmp");
try
{
PdfOptions exportOptions = new PdfOptions();
exportOptions.setPdfDocumentInfo(new PdfDocumentInfo());
image.save(outputFile, exportOptions);
}
finally
{
image.close();
}
// Load a GIF image
String dataDir = "/anyDir/";
try (GifImage gif = (GifImage)Image.load(dataDir + "aspose-logo.gif"))
{
// iterate through array of blocks in the GIF image
IGifBlock[] blocks = gif.getBlocks();
for (int i = 0; i < blocks.length; i++)
{
// Check if it is not a gif block then ignore it
if (!(blocks[i] instanceof GifFrameBlock))
continue;
// convert block to GifFrameBlock class instance
GifFrameBlock gifBlock = ((GifFrameBlock) (blocks[i]));
// Create an instance of TIFF Option class
TiffOptions objTiff = new TiffOptions(TiffExpectedFormat.Default);
// Save the GIFF block as TIFF image
gifBlock.save(dataDir + "asposelogo" + i + "_out.tif", objTiff);
}
}
String[] paths = new String[]
{
"C:\\test\\butterfly.gif",
"C:\\test\\33715-cmyk.jpeg",
"C:\\test\\3.JPG",
"C:\\test\\test.j2k",
"C:\\test\\Rings.png",
"C:\\test\\3layers_maximized_comp.psd",
"C:\\test\\img4.TIF",
"C:\\test\\Lossy5.webp"
};
for (String path : paths)
{
String destPath = path + ".svg";
Image image = Image.load(path);
try
{
SvgOptions svgOptions = new SvgOptions();
SvgRasterizationOptions svgRasterizationOptions = new SvgRasterizationOptions();
svgRasterizationOptions.setPageWidth(image.getWidth());
svgRasterizationOptions.setPageHeight(image.getHeight());
svgOptions.setVectorRasterizationOptions(svgRasterizationOptions);
image.save(destPath, svgOptions);
}
finally
{
image.close();
}
}
// Load the image
Image image = Image.load(dataDir + "aspose-logo.svg");
try
{
// Create an instance of PNG options
PngOptions pngOptions = new PngOptions();
SvgRasterizationOptions svgOptions = new SvgRasterizationOptions();
svgOptions.setPageWidth(100);
svgOptions.setPageHeight(200);
pngOptions.setVectorRasterizationOptions(svgOptions);
// Save the results to disk
image.save(dataDir + "ConvertingSVGToRasterImages_out.png", pngOptions);
}
finally
{
image.close();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
Image image = Image.load(dataDir+"mysvg.svg");
try
{
image.save(dataDir+"yoursvg.svg");
}
finally
{
image.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String dataDir = Utils.getSharedDataDir(ExpandandCropImages.class) + "ConvertingImages/";
RasterImage rasterImage = (RasterImage) Image.load(dataDir + "aspose-logo.jpg");
// setting for image data to be cashed
rasterImage.cacheData();
// Create an instance of Rectangle class and define X,Y and Width, height of the rectangle.
Rectangle destRect = new Rectangle(200, 200, 300, 300);
// Save output image by passing output file name, image options and rectangle object.
rasterImage.save(dataDir + "ExpandandCropImages_out.jpg", new JpegOptions(), destRect);
// Create temporary image.
java.io.File tmp = java.io.File.createTempFile("image", "tes");
// Delete the file. This statement should execute to make it sure that resource is properly disposed off.
tmp.deleteOnExit();
// Path & name of existing image.
String imageDataPath = tmp.getAbsolutePath();
// Create the stream of the existing image file.
java.io.InputStream fileStream = new java.io.FileInputStream(tmp);
try
{
// Create an instance of BMP image option class.
com.aspose.imaging.imageoptions.BmpOptions bmpOptions = new com.aspose.imaging.imageoptions.BmpOptions();
try
{
bmpOptions.setBitsPerPixel(32);
// Set the source property of the imaging option class object.
bmpOptions.setSource(new com.aspose.imaging.sources.StreamSource(fileStream));
// Do processing.
// Following is the sample processing on the image. Un-comment to use it.
// com.aspose.imaging.RasterImage image = (com.aspose.imaging.RasterImage)com.aspose.imaging.Image.create(bmpOptions, 10, 10);
// try
// {
// com.aspose.imaging.Color[] pixels = new com.aspose.imaging.Color[4];
// for (int i = 0; i < 4; ++i)
// {
// pixels[i] = com.aspose.imaging.Color.fromArgb(40, 30, 20, 10);
// }
// image.savePixels(new com.aspose.imaging.Rectangle(0, 0, 2, 2), pixels);
// image.save(imageDataPath);
//}
//finally
//{
// This statement is in the final block because in any case this statement should execute to make it sure that resource is properly closed.
// image.close();
//}
}
finally
{
// This statement is in the final block because in any case this statement should execute to make it sure that resource is properly closed.
bmpOptions.close();
}
}
finally
{
// This statement is in the final block because in any case this statement should execute to make it sure that resource is properly disposed off.
fileStream.close();
fileStream = null;
}
String dataDir = "/PathToImageDir/";
// Load an image in an instance of Image
try (Image image = Image.load(dataDir + "aspose-logo.jpg"))
{
// Cast the image to RasterCachedImage
RasterCachedImage rasterCachedImage = (RasterCachedImage) image;
// Check if image is cached
if (!rasterCachedImage.isCached()) {
// Cache image if not already cached
rasterCachedImage.cacheData();
}
// Transform image to its grayscale representation
rasterCachedImage.grayscale();
// Save the resultant image
rasterCachedImage.save(dataDir + "Grayscaling_out.jpg");
}
String dataDir = Utils.getSharedDataDir(PNGToPDF.class) + "ConvertingImages/";
PngImage pngImage = (PngImage) Image.load(dataDir + "aspose_logo.png");
try
{
PdfOptions exportOptions = new PdfOptions();
exportOptions.setPdfDocumentInfo(new PdfDocumentInfo());
pngImage.save("multipage_specificColor_.djvu4_ethalon.pdf", exportOptions);
}
finally
{
pngImage.close();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
Image image = Image.load(dataDir);
try
{
PsdImage psdImage = (PsdImage)image;
PdfOptions exportOptions = new PdfOptions();
exportOptions.setPdfDocumentInfo(new com.aspose.imaging.fileformats.pdf.PdfDocumentInfo());
psdImage.save(dataDir+"result.pdf", exportOptions);
}
finally
{
image.dispose();
}
String dataDir = Utils.getSharedDataDir(RasterImageToPDF.class) + "ConvertingImages/";
String destFilePath = "transparent_orig.gif.pdf";
Image image = Image.load(dataDir);
try
{
image.save(destFilePath, new PdfOptions());
}
finally
{
image.dispose();
}
import com.aspose.imaging.Rectangle;
import com.aspose.imaging.fileformats.tiff.TiffFrame;
import com.aspose.imaging.fileformats.tiff.TiffImage;
import com.aspose.imaging.fileformats.tiff.enums.TiffExpectedFormat;
import com.aspose.imaging.fileformats.tiff.enums.TiffPhotometrics;
import com.aspose.imaging.imageoptions.TiffOptions;
import com.aspose.imaging.xmp.*;
import com.aspose.imaging.xmp.schemas.dublincore.DublinCorePackage;
import com.aspose.imaging.xmp.schemas.photoshop.ColorMode;
import com.aspose.imaging.xmp.schemas.photoshop.PhotoshopPackage;
// Specify the size of image by defining a Rectangle
Rectangle rect = new Rectangle(0, 0, 100, 200);
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.TiffJpegRgb);
tiffOptions.setPhotometric(TiffPhotometrics.MinIsBlack);
tiffOptions.setBitsPerSample(new int[] { 8 });
// create the brand new image just for sample purposes
TiffImage image = new TiffImage(new TiffFrame(tiffOptions, rect.getWidth(), rect.getHeight()));
try
{
// create an instance of XMP-Header
XmpHeaderPi xmpHeader = new XmpHeaderPi(UUID.randomUUID().toString());
// create an instance of Xmp-TrailerPi
XmpTrailerPi xmpTrailer = new XmpTrailerPi(true);
// create an instance of XMPmeta class to set different attributes
XmpMeta xmpMeta = new XmpMeta();
xmpMeta.addAttribute("Author", "Mr Smith");
xmpMeta.addAttribute("Description", "The fake metadata value");
// create an instance of XmpPacketWrapper that contains all metadata
XmpPacketWrapper xmpData = new XmpPacketWrapper(xmpHeader, xmpTrailer, xmpMeta);
// create an instance of Photoshop package and set photoshop attributes
PhotoshopPackage photoshopPackage = new PhotoshopPackage();
photoshopPackage.setCity("London");
photoshopPackage.setCountry("England");
photoshopPackage.setColorMode(ColorMode.Rgb);
photoshopPackage.setCreatedDate(new Date());
// add photoshop package into XMP metadata
xmpData.addPackage(photoshopPackage);
// create an instance of DublinCore package and set dublinCore attributes
DublinCorePackage dublinCorePackage = new DublinCorePackage();
dublinCorePackage.setAuthor("Charles Bukowski");
dublinCorePackage.setTitle("Confessions of a Man Insane Enough to Live With the Beasts");
dublinCorePackage.addValue("dc:movie", "Barfly");
// add dublinCore Package into XMP metadata
xmpData.addPackage(dublinCorePackage);
// update XMP metadata into image
image.setXmpData(xmpData);
try (ByteArrayOutputStream mem = new ByteArrayOutputStream())
{
// Save image on the disk or in memory stream
image.save(mem);
// Load the image from memory stream or from disk to read/get the metadata
try (TiffImage img = (TiffImage)Image.load(new ByteArrayInputStream(mem.toByteArray())))
{
// Getting the XMP metadata
XmpPacketWrapper imgXmpData = img.getXmpData();
for (XmpPackage pkg : imgXmpData.getPackages())
{
// Use package data ...
}
}
}
}
finally
{
image.close();
}
String sourceFilePath = "testTileDeflate.tif";
String outputFilePath = "testTileDeflate Cmyk.tif";
TiffOptions options = new TiffOptions(TiffExpectedFormat.TiffLzwCmyk);
Image image = Image.load(sourceFilePath);
try
{
image.save(outputFilePath, options);
}
finally
{
image.close();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
Image image = Image.load(dataDir+"test.bmp");
try
{
image.save("test.bmp.png", new PngOptions());
}
finally
{
image.dispose();
}
String[] files = new String[] {"example.odg", "example1.odg"};
String folder = "C:\\Temp\\";
final OdgRasterizationOptions rasterizationOptions = new OdgRasterizationOptions();
for (String file : files)
{
String fileName = folder + file;
Image image = Image.load(fileName);
try
{
rasterizationOptions.setPageSize(new SizeF(image.getWidth(), image.getHeight()));
String outFileName = fileName.replace(".odg", ".png");
image.save(outFileName,
new PngOptions()
{{
setVectorRasterizationOptions(rasterizationOptions);
}});
outFileName = fileName.replace(".odg", ".pdf");
image.save(outFileName,
new PdfOptions()
{{
setVectorRasterizationOptions(rasterizationOptions);
}});
}
finally
{
image.dispose();
}
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
public static void main(String... args) throws Exception {
String dataDir = Utils.getSharedDataDir(SVGToEMFConversion.class) + "ConvertingImages/";
String[] testFiles = new String[]
{
"input.svg",
"juanmontoya_lingerie.svg",
"rg1024_green_grapes.svg",
"sample_car.svg",
"tommek_Car.svg"
};
String basePath = dataDir+"IMAGINGJAVA-1085\\";
String outputPath = basePath + "output\\";
File dir = new File(outputPath);
if (!dir.exists())
{
assert dir.mkdirs() : "Can not create output directory!";
}
for (String fileName : testFiles)
{
String inputFileName = basePath + fileName;
String outputFileName = outputPath + fileName + ".emf";
final Image image = Image.load(inputFileName);
try
{
image.save(outputFileName, new EmfOptions()
{{
setVectorRasterizationOptions(new SvgRasterizationOptions()
{{
setPageSize(Size.to_SizeF(image.getSize()));
}});
}});
}
finally
{
image.close();
}
}
}
// create new synchronized two-way stream
com.aspose.imaging.StreamContainer streamContainer = new com.aspose.imaging.StreamContainer(new java.io.ByteArrayInputStream(new byte[0]));
try
{
// check if the access to the stream source is synchronized.
synchronized (streamContainer.getSyncRoot())
{
// do work
// now access to streamContainer is synchronized
}
}
finally
{
streamContainer.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String inputFile = dataDir + "image.dcm";
String outputFile = dataDir + "AdjustingBrightness_out.bmp";
File file = new File(inputFile);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
// Load a DICOM image in an instance of DicomImage
com.aspose.imaging.fileformats.dicom.DicomImage image = new com.aspose.imaging.fileformats.dicom.DicomImage(fis);
//yar Image image = Image.load(dataDir + "aspose-logo.dxf");
// Adjust the brightness
image.adjustBrightness(50);
// Create an instance of BmpOptions for the resultant image and Save the
// resultant image
image.save(outputFile, new com.aspose.imaging.imageoptions.BmpOptions());
}
catch (FileNotFoundException ex) {
Logger.getLogger(AdjustingBrightness.class.getName()).log(Level.SEVERE, null, ex);
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String inputFile = dataDir + "image.dcm";
String outputFile = dataDir + "AdjustingContrast_out.bmp";
// Load a DICOM image in an instance of DicomImage
File file = new File(inputFile);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
// Load a DICOM image in an instance of DicomImage
com.aspose.imaging.fileformats.dicom.DicomImage image = new com.aspose.imaging.fileformats.dicom.DicomImage(fis);
// Adjust the contrast
image.adjustContrast(50);
// Create an instance of BmpOptions for the resultant image and Save the
// resultant image
image.save(outputFile, new com.aspose.imaging.imageoptions.BmpOptions());
}
catch (FileNotFoundException ex)
{
Logger.getLogger(AdjustingBrightness.class.getName()).log(Level.SEVERE, null, ex);
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String inputFile = dataDir + "image.dcm";
String outputFile = dataDir + "AdjustingGamma.bmp";
File file = new File(inputFile);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
// Load a DICOM image in an instance of DicomImage
com.aspose.imaging.fileformats.dicom.DicomImage image = new com.aspose.imaging.fileformats.dicom.DicomImage(fis);
// Adjust the gamma
image.adjustGamma(50);
// Create an instance of BmpOptions for the resultant image and Save the
// resultant image
image.save(outputFile, new com.aspose.imaging.imageoptions.BmpOptions());
}
catch (FileNotFoundException ex)
{
Logger.getLogger(AdjustingBrightness.class.getName()).log(Level.SEVERE, null, ex);
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String inputFile = dataDir + "image.dcm";
String outputFile = dataDir + "ApplyFilterOnDICOMImage_out.bmp";
File file = new File(inputFile);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
// Load a DICOM image in an instance of DicomImage
com.aspose.imaging.fileformats.dicom.DicomImage image = new com.aspose.imaging.fileformats.dicom.DicomImage(fis);
// Load an image
// Supply the filters to DICOM image.
image.filter(image.getBounds(), new com.aspose.imaging.imagefilters.filteroptions.MedianFilterOptions(8));
// Save the results to output path.
image.save(outputFile, new com.aspose.imaging.imageoptions.BmpOptions());
}
catch (FileNotFoundException ex)
{
Logger.getLogger(AdjustingBrightness.class.getName()).log(Level.SEVERE, null, ex);
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String inputFile = dataDir + "image.dcm";
String outputFile = dataDir + "BinarizationwithBradleyAdaptiveThreshold_out.bmp";
File file = new File(inputFile);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
// Load a DICOM image in an instance of DicomImage
com.aspose.imaging.fileformats.dicom.DicomImage image = new com.aspose.imaging.fileformats.dicom.DicomImage(fis);
// Binarize image with bradley's adaptive threshold.
image.binarizeBradley(10);
// Save the resultant image.
image.save(outputFile, new com.aspose.imaging.imageoptions.BmpOptions());
}
catch (FileNotFoundException ex)
{
Logger.getLogger(AdjustingBrightness.class.getName()).log(Level.SEVERE, null, ex);
}
import com.aspose.imaging.*;
import com.aspose.imaging.imageoptions.BmpOptions;
String inputFile = dataDir + "image.dcm";
String outputFile = dataDir + "BinarizationwithFixedThreshold_out.bmp";
// Load a DICOM image in an instance of DicomImage
try (Image image = new Image.load(inputFile))
{
// Binarize image with predefined fixed threshold.
image.binarizeFixed((byte) 100);
// Save the resultant image.
image.save(outputFile, new BmpOptions());
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String inputFile = dataDir + "image.dcm";
String outputFile = dataDir + "BinarizationwithOtsuThreshold_out.bmp";
File file = new File(inputFile);
FileInputStream fis = null;
fis = new FileInputStream(file);
// Load a DICOM image in an instance of DicomImage
com.aspose.imaging.fileformats.dicom.DicomImage image = new com.aspose.imaging.fileformats.dicom.DicomImage(fis);
// Binarize image with Otsu Thresholding.
image.binarizeOtsu();
// Save the resultant image.
image.save(outputFile, new com.aspose.imaging.imageoptions.BmpOptions());
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String inputFile = dataDir + "image.dcm";
String outputFile = dataDir + "CropbyShifts_out.bmp";
File file = new File(inputFile);
FileInputStream fis = null;
//try {
fis = new FileInputStream(file);
// Load a DICOM image in an instance of DicomImage
com.aspose.imaging.fileformats.dicom.DicomImage image = new com.aspose.imaging.fileformats.dicom.DicomImage(fis);
// Call and supply the four values to Crop method.
image.crop(10, 20, 30, 40);
// Save the results to disk
image.save(outputFile, new com.aspose.imaging.imageoptions.BmpOptions());
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String inputFile = dataDir + "image.dcm";
String outputFile = dataDir + "DitheringForDICOMImage_out.bmp";
File file = new File(inputFile);
FileInputStream fis = null;
fis = new FileInputStream(file);
// Load a DICOM image in an instance of DicomImage
com.aspose.imaging.fileformats.dicom.DicomImage image = new com.aspose.imaging.fileformats.dicom.DicomImage(fis);
// Peform Threshold dithering on the image
image.dither(com.aspose.imaging.DitheringMethod.ThresholdDithering, 1);
// Save the image
image.save(outputFile, new com.aspose.imaging.imageoptions.BmpOptions());
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String dataDir = Utils.getSharedDataDir(FlipDICOMImage.class) + "dicom/";
String inputFile = dataDir + "image.dcm";
String outputFile = "FlipDICOMImage_out.bmp";
File file = new File(inputFile);
FileInputStream fis = null;
fis = new FileInputStream(file);
// Load a DICOM image in an instance of DicomImage
com.aspose.imaging.fileformats.dicom.DicomImage image = new com.aspose.imaging.fileformats.dicom.DicomImage(fis);
image.rotateFlip(com.aspose.imaging.RotateFlipType.Rotate180FlipNone);
image.save(outputFile, new com.aspose.imaging.imageoptions.BmpOptions());
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String inputFile = dataDir + "image.dcm";
String outputFile = dataDir + "Grayscaling_out.bmp";
// Load an existing image.
File file = new File(inputFile);
FileInputStream fis = null;
fis = new FileInputStream(file);
// Load a DICOM image in an instance of DicomImage
com.aspose.imaging.fileformats.dicom.DicomImage image = new com.aspose.imaging.fileformats.dicom.DicomImage(fis);
// Transform image to its grayscale representation
image.grayscale();
// Save the resultant image.
image.save(outputFile, new com.aspose.imaging.imageoptions.BmpOptions());
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String inputFile = dataDir + "image.dcm";
String outputFile = dataDir + "ResizeHeightProportionally_out.bmp";
File file = new File(inputFile);
FileInputStream fis = null;
fis = new FileInputStream(file);
// Load a DICOM image in an instance of DicomImage
com.aspose.imaging.fileformats.dicom.DicomImage image = new com.aspose.imaging.fileformats.dicom.DicomImage(fis);
image.resizeHeightProportionally(100, ResizeType.AdaptiveResample);
image.save(outputFile, new com.aspose.imaging.imageoptions.BmpOptions());
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String inputFile = dataDir + "image.dcm";
String outputFile = dataDir + "ResizeWidthProportionally_out.bmp";
File file = new File(inputFile);
FileInputStream fis = null;
fis = new FileInputStream(file);
// Load a DICOM image in an instance of DicomImage
com.aspose.imaging.fileformats.dicom.DicomImage image = new com.aspose.imaging.fileformats.dicom.DicomImage(fis);
image.resizeWidthProportionally(150, ResizeType.AdaptiveResample);
image.save(outputFile, new com.aspose.imaging.imageoptions.BmpOptions());
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String inputFile = dataDir + "image.dcm";
String outputFile = dataDir + "RotateDICOMImage_out.bmp";
File file = new File(inputFile);
FileInputStream fis = null;
fis = new FileInputStream(file);
// Load a DICOM image in an instance of DicomImage
com.aspose.imaging.fileformats.dicom.DicomImage image = new com.aspose.imaging.fileformats.dicom.DicomImage(fis);
image.rotate(10);
image.save(outputFile, new com.aspose.imaging.imageoptions.BmpOptions());
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String inputFile = dataDir + "image.dcm";
String outputFile = dataDir + "SimpleResizing_out.bmp";
File file = new File(inputFile);
FileInputStream fis = null;
fis = new FileInputStream(file);
// Load a DICOM image in an instance of DicomImage
com.aspose.imaging.fileformats.dicom.DicomImage image = new com.aspose.imaging.fileformats.dicom.DicomImage(fis);
image.resize(200, 200);
image.save(outputFile, new com.aspose.imaging.imageoptions.BmpOptions());
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//Load a DjVu image
try (DjvuImage image = (DjvuImage) Image.load(dataDir + "Sample.djvu"))
{
//Create an instance of PngOptions
PngOptions exportOptions = new PngOptions();
//Set ColorType to Grayscale
exportOptions.setColorType(PngColorType.Grayscale);
//Create an instance of Rectangle and specify the portion on DjVu page
Rectangle exportArea = new Rectangle(0, 0, 2000, 2000);
//Specify the DjVu page index
int exportPageIndex = 2;
//Initialize an instance of DjvuMultiPageOptions
//while passing index of DjVu page index and instance of Rectangle
//covering the area to be exported
exportOptions.setMultiPageOptions(new DjvuMultiPageOptions(exportPageIndex, exportArea));
//Save the image
image.save(dataDir + "ConvertDjvuPagePortionToImage_out.png", exportOptions);
System.out.println("File conveted");
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//Load a DjVu image
DjvuImage image = (DjvuImage) Image.load(dataDir + "Sample.djvu");
//Create an instance of GifOptions with its default constructor
GifOptions exportOptions = new GifOptions();
//Set the resolution of resultant image
exportOptions.setResolutionSettings(new ResolutionSetting(300, 300));
//Set PaletteCorrection to false
exportOptions.setDoPaletteCorrection(false);
//Create an instance of 8bit palette and set it as Palette property for instance of GifOptions
exportOptions.setPalette(ColorPaletteHelper.create8Bit());
//Create an instance of IntRange and initialize it with range of pages to be exported
IntRange range = new IntRange(0, 2); //Export first 2 pages
//Initialize an instance of DjvuMultiPageOptions while passing instance of IntRange
exportOptions.setMultiPageOptions(new DjvuMultiPageOptions(range));
//Call Save method while passing instance of GifOptions
image.save(dataDir + "ConvertDjvuPagesToGif_out.gif", exportOptions);
System.out.println("File conveted");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//Load a DjVu image
DjvuImage image = (DjvuImage) Image.load(dataDir + "Sample.djvu");
//Create an instance of BmpOptions
BmpOptions exportOptions = new BmpOptions();
//Set BitsPerPixel for resultant images
exportOptions.setBitsPerPixel(32);
//Create an instance of IntRange and initialize it with range of pages to be exported
IntRange range = new IntRange(0, 2); //Export first 2 pages
int counter = 0;
for (int i : range.getRange()) {
//Save each page in separate file, as BMP do not support layering
exportOptions.setMultiPageOptions(new DjvuMultiPageOptions(range.getArrayOneItemFromIndex(counter)));
String output = dataDir + "ConvertDjvuPagesToImages_out" + (counter++) + ".bmp";
image.save(output, exportOptions);
}
// Display Status.
System.out.println("File conveted");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//Load a DjVu image
DjvuImage image = (DjvuImage) Image.load(dataDir + "Sample.djvu");
//Create an instance of TiffOptions & use preset options for Black n While with Deflate compression
TiffOptions exportOptions = new TiffOptions(TiffExpectedFormat.TiffDeflateBw);
//Create an instance of IntRange and initialize it with range of pages to be exported
IntRange range = new IntRange(0, 2); //Export first 2 pages
//Initialize the DjvuMultiPageOptions
exportOptions.setMultiPageOptions(new DjvuMultiPageOptions(range));
//Call Save method while passing instance of TiffOptions
image.save(dataDir + "ConvertDjvuPagesToTiff_out.tiff", exportOptions);
// Display Status.
System.out.println("File conveted");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//Load a DjVu image
DjvuImage image = (DjvuImage) Image.load(dataDir + "Sample.djvu");
//Create an instance of PdfOptions
PdfOptions exportOptions = new PdfOptions();
//Initialize the metadata for Pdf document
exportOptions.setPdfDocumentInfo(new PdfDocumentInfo());
//Create an instance of IntRange and initialize it with the range of DjVu pages to be exported
IntRange range = new IntRange(0, 3); //Export first 3 pages
//Initialize an instance of DjvuMultiPageOptions with range of DjVu pages to be exported
exportOptions.setMultiPageOptions(new DjvuMultiPageOptions(range));
//Save the result in PDF format
image.save(dataDir + "ConvertDjvuToPdf_out.pdf", exportOptions);
// Display Status.
System.out.println("File conveted");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//Load a DjVu image
DjvuImage image = (DjvuImage) Image.load(dataDir + "Sample.djvu");
//Create an instance of TiffOptions & use preset options for Black n While with Deflate compression
TiffOptions exportOptions = new TiffOptions(TiffExpectedFormat.TiffDeflateBw);
//Initialize the DjvuMultiPageOptions
exportOptions.setMultiPageOptions(new DjvuMultiPageOptions());
//Call Save method while passing instance of TiffOptions
image.save(dataDir + "ConvertDjvuToTiff_out.tiff", exportOptions);
// Display Status.
System.out.println("File conveted");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load a DjVu image
DjvuImage image = (DjvuImage) Image.load(dataDir + "Sample.djvu");
// Create an instance of BmpOptions
BmpOptions exportOptions = new BmpOptions();
// Set BitsPerPixel for resultant images
exportOptions.setBitsPerPixel(32);
// Create an instance of IntRange and initialize it with range of pages
// to be exported
IntRange range = new IntRange(0, 2); //Export first 2 pages
int counter = 0;
for (int i : range.getRange()) {
// Save each page in separate file, as BMP do not support layering
exportOptions.setMultiPageOptions(new DjvuMultiPageOptions(range.getArrayOneItemFromIndex(counter)));
image.save(String.format("{0}.bmp", counter++), exportOptions);
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load a DjVu image
DjvuImage image = (DjvuImage) Image.load(dataDir + "Sample.djvu");
// Create an instance of PngOptions
PngOptions exportOptions = new PngOptions();
// Set ColorType to Grayscale
exportOptions.setColorType(PngColorType.Grayscale);
// Create an instance of Rectangle and specify the portion on DjVu page
Rectangle exportArea = new Rectangle(0, 0, 500, 500);
// Specify the DjVu page index
int exportPageIndex = 2;
// Initialize an instance of DjvuMultiPageOptions
// while passing index of DjVu page index and instance of Rectangle
// covering the area to be exported
exportOptions.setMultiPageOptions(new DjvuMultiPageOptions(exportPageIndex, exportArea));
// Save the image
image.save(dataDir + "ConvertSpecificPortionOfDjVuPage_out.djvu", exportOptions);
String dir = Utils.getSharedDataDir(ParallelDJVUImagesProcessingUsingMultithreading.class) + "djvu/";
final String fileName = dir + "Sample.djvu";
final String filePath = dir + "Sample.djvu";
String outDir = dir;
int numThreads = 20;
ExecutorService execServ = Executors.newFixedThreadPool(numThreads);
for (int i = 0; i < numThreads; i++)
{
final String outputFile = outDir + fileName + "_task" + i+ ".png";
execServ.execute(new Runnable()
{
@Override
public void run()
{
RandomAccessFile fs;
try
{
fs = new RandomAccessFile(fileName, "r");
}
catch (FileNotFoundException e)
{
throw new RuntimeException(e.getMessage(), e);
}
try
{
Image image = Image.load(fs);
try
{
image.save(outputFile, new PngOptions());
}
finally
{
image.close();
}
}
finally
{
try
{
fs.close();
}
catch (IOException ignore)
{
}
}
}
});
}
execServ.shutdown();
while (!execServ.awaitTermination(1, TimeUnit.SECONDS))
{
Thread.yield();
}
String dataDir = Utils.getSharedDataDir(CropEMFFile.class) + "EMF/";
EmfImage image = (EmfImage)Image.load(dataDir + "test.emf");
image.crop(new Rectangle(10, 10, 100, 150));
System.out.println(image.getWidth());
System.out.println(image.getHeight());
image.save(dataDir + "test.emf_crop.emf");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String dataDir = Utils.getSharedDataDir(SupportForEPS.class) + "EPS/";
EpsImage epsImage = (EpsImage)Image.load(dataDir+"anyEpsFile.eps");
try
{
// check if EPS image has any raster preview to proceed (for now only raster preview is supported)
if (epsImage.hasRasterPreview())
{
if (epsImage.getPhotoshopThumbnail() != null)
{
// process Photoshop thumbnail if it's present
}
if (epsImage.getEpsType() == EpsType.Interchange)
{
// Get EPS Interchange subformat instance
EpsInterchangeImage epsInterchangeImage = (EpsInterchangeImage)epsImage;
if (epsInterchangeImage.getRasterPreview() != null)
{
// process black-and-white Interchange raster preview if it's present
}
}
else
{
// Get EPS Binary subformat instance
EpsBinaryImage epsBinaryImage = (EpsBinaryImage)epsImage;
if (epsBinaryImage.getTiffPreview() != null)
{
// process TIFF preview if it's present
}
if (epsBinaryImage.getWmfPreview() != null)
{
// process WMF preview if it's present
}
}
// export EPS image to PNG (by default, best available quality preview is used for export)
epsImage.save(dataDir+"anyEpsFile.png", new PngOptions());
}
}
finally
{
epsImage.close();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//Load an existing image
com.aspose.imaging.Image image = com.aspose.imaging.Image.load(dataDir + "sample.bmp");
//Create an instance of PsdSaveOptions class
//Create an instance of PsdSaveOptions class
com.aspose.imaging.imageoptions.PsdOptions saveOptions = new com.aspose.imaging.imageoptions.PsdOptions();
//Set the CompressionMethod as Raw
//Note: Other supported CompressionMethod is CompressionMethod.Rle [No Compression]
saveOptions.setCompressionMethod(CompressionMethod.Raw);
//Set the ColorMode to GrayScale//Note: Other supported ColorModes are ColorModes.Bitmap and ColorModes.RGB
saveOptions.setColorMode(ColorModes.Rgb);
//Save the image to disk location with supplied PsdOptions settings
image.save(dataDir + "ExportImageToPSD_out.psd", saveOptions);
// Display Status.
System.out.println("Image exported to PSD successfully!");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String inputPath = dataDir + "conic_pyramid.dxf";
Image image = Image.load(dataDir + "sample.psd");
PsdImage psdImage = (PsdImage) image;
PngOptions pngOptions = new PngOptions();
pngOptions.setColorType(PngColorType.TruecolorWithAlpha);
for (int i = 0; i < psdImage.getLayers().length; i++) {
psdImage.getLayers()[i].save(dataDir + "ExportPsdLayersToImages_out" + i + ".png", pngOptions);
}
String sourcepath = dataDir + "aspose_logo.png";
String outputPath = dataDir + "UseBradleythresholding_out.png";
// Load an existing image.
com.aspose.imaging.fileformats.png.PngImage objimage = (com.aspose.imaging.fileformats.png.PngImage)
com.aspose.imaging.Image.load(sourcepath);
try
{
// Define threshold value
double threshold = 0.15;
// Call BinarizeBradley method and pass the threshold value as parameter
objimage.binarizeBradley(threshold);
// Save the output image
objimage.save(outputPath);
}
finally
{
objimage.close();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//Creates an instance of BmpOptions and set its various properties
com.aspose.imaging.imageoptions.BmpOptions createOptions = new com.aspose.imaging.imageoptions.BmpOptions();
createOptions.setBitsPerPixel(24);
//Create an instance of FileCreateSource and assign it as Source for the instance of BmpOptions
//If second parameter is not passed, then by default the file has IsTemporal set to True
createOptions.setSource(new com.aspose.imaging.sources.FileCreateSource(dataDir + "sample.bmp"));
try
{
//Creates an instance of Image
try (com.aspose.imaging.Image image = com.aspose.imaging.Image.create(createOptions, 500, 500))
{
image.save();
}
// Display Status.
System.out.println("Image created successfully!");
}
finally
{
createOptions.close();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
com.aspose.imaging.Metered metered = new com.aspose.imaging.Metered();
// Access the setMeteredKey property and pass public and private keys as parameters
metered.setMeteredKey("<valid pablic key>", "<valid private key>");
// Get consumed qantity value before accessing API
System.out.println("Consumption quantity" + com.aspose.imaging.Metered.getConsumptionQuantity());
// DO PROCESSING
//com.aspose.imaging.Image img = com.aspose.imaging.Image.load("C:\\in.psd");
//img.save("C:\\Temp\\out.psd");
//Since upload data is running on another thread, so we need wait some time
//java.lang.Thread.sleep(10000);
// get metered data amount
System.out.println("Consumption quantity" + com.aspose.imaging.Metered.getConsumptionQuantity());
}
//Create an Image object and load an existing file using the file path
com.aspose.imaging.Image image = com.aspose.imaging.Image.load(dataDir + "sample.bmp");
try
{
//Print message
System.out.println("Image is loaded successfully.");
}
finally
{
image.close();
}
// Open an existing file using the Stream
try (com.aspose.imaging.Image image = com.aspose.imaging.Image.load(stream))
{
// do some image processing
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(ReadingPixelVaules.class) + "files/";
//String dir = "C:\\Errors\\1006\\";
String fileName = "16bit Uncompressed, BigEndian, Rgb, Contiguous Gamma1.0.tif";
// ICC profile is not applied for 16-bit color components at the moment, so disable that option explicitly.
LoadOptions loadOptions = new LoadOptions();
loadOptions.setUseIccProfileConversion(false);
Rectangle desiredArea = new Rectangle(470, 1350, 30, 30);
RasterImage image = (RasterImage)Image.load(dataDir + fileName, loadOptions);
try
{
long[] colors64Bit = image.loadArgb64Pixels(image.getBounds());
int alpha, red, green, blue;
for (int y = desiredArea.getTop(); y < desiredArea.getBottom(); ++y)
{
for (int x = desiredArea.getLeft(); x < desiredArea.getRight(); ++x)
{
int offset = y * image.getWidth() + x;
long color64 = colors64Bit[offset];
alpha = (int)((color64 >> 48) & 0xffff);
red = (int)((color64 >> 32) & 0xffff);
green = (int)((color64 >> 16) & 0xffff);
blue = (int)(color64 & 0xffff);
System.out.format("A=%X, R=%X, G=%X, B=%X\n", alpha, red, green, blue);
}
}
}
finally{
image.dispose();
}
try (Image image = Image.load(dataDir + "aspose-logo.jpg"))
{
image.save("SavingtoDisk_out.jpg");
}
try (java.io.OutputStream os = new java.io.FileOutputStream("C:\\SavingtoStream_out.jpg"))
{
try (Image image = Image.load(dataDir + "aspose-logo.jpg"))
{
//Save the image using the Save method exposed by the Image class and pass the outputstream object
image.save(os);
}
}
String dataDir = "dataDir/";
// Create an instance of TiffImage and load the copied destination image
try (TiffImage image1 = (TiffImage) com.aspose.imaging.Image.load(dataDir + "TestDemo.tif"))
{
// Create an instance of TiffImage and load the source image
try (TiffImage image2 = (TiffImage) com.aspose.imaging.Image.load(dataDir + "sample.tif"))
{
// Create an instance of TIffFrame and copy active frame of source image
TiffFrame frame = TiffFrame.copyFrame(image2.getActiveFrame());
// Add copied frame to destination image
image1.addFrame(frame);
// save the image with changes.
image.Save(dataDir + "ConcatTIFFImages_out.tiff");
}
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//Create an instance of BmpCreateOptions and set its various properties
com.aspose.imaging.imageoptions.BmpOptions createOptions = new com.aspose.imaging.imageoptions.BmpOptions();
createOptions.setBitsPerPixel(24);
//Create an instance of FileCreateSource and assign it to Source property
createOptions.setSource(new com.aspose.imaging.sources.FileCreateSource(dataDir + "sample.bmp",false));
//Create an instance of RasterImage
RasterImage rasterImage = (RasterImage) RasterImage.create(createOptions, 500, 500);
//Get the pixels of the image by specifying the area as image boundary
com.aspose.imaging.Color [] pixels = rasterImage.loadPixels(rasterImage.getBounds());
for (int index = 0; index < pixels.length; index++)
{
//Set the indexed pixel color to yellow
pixels[index] = com.aspose.imaging.Color.getYellow();
}
rasterImage.savePixels(rasterImage.getBounds(), pixels);
// Save processed image.
rasterImage.save();
// Display Status.
System.out.println("Processing completed successfully!");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Creates an instance of BmpOptions and set its various properties
com.aspose.imaging.imageoptions.BmpOptions bmpCreateOptions = new com.aspose.imaging.imageoptions.BmpOptions();
bmpCreateOptions.setBitsPerPixel(32);
// Define the source property for the instance of BmpCreateOptions
bmpCreateOptions.setSource(
new com.aspose.imaging.sources.StreamSource(new java.io.ByteArrayInputStream(new byte[100 * 100 * 4])));
// Creates an instance of Image and call Create method by passing the
// BmpOptions object
com.aspose.imaging.Image image = com.aspose.imaging.Image.create(bmpCreateOptions, 100, 100);
// Create and initialize an instance of Graphics class
com.aspose.imaging.Graphics graphic = new com.aspose.imaging.Graphics(image);
// Clear the image surface with Yellow color
graphic.clear(com.aspose.imaging.Color.getYellow());
// Draw a dotted arc shape by specifying the Pen object having red black
// color and coordinates, height, width, start & end angles
int width = 100;
int height = 200;
int startAngle = 45;
int sweepAngle = 270;
// Draw arc to screen.
graphic.drawArc(new Pen(com.aspose.imaging.Color.getBlack()), 0, 0, width, height, startAngle, sweepAngle);
// Save all changes.
image.save(dataDir + "DrawingArc_out.bmp");
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
com.aspose.imaging.imageoptions.BmpOptions bmpCreateOptions = new com.aspose.imaging.imageoptions.BmpOptions();
bmpCreateOptions.setBitsPerPixel(32);
// Define the source property for the instance of BmpOptions
bmpCreateOptions.setSource(
new com.aspose.imaging.sources.StreamSource(new java.io.ByteArrayInputStream(new byte[100 * 100 * 4])));
// Creates an instance of Image and call create method by passing the
// bmpCreateOptions object
com.aspose.imaging.Image image = com.aspose.imaging.Image.create(bmpCreateOptions, 100, 100);
// Create and initialize an instance of Graphics class
com.aspose.imaging.Graphics graphic = new com.aspose.imaging.Graphics(image);
// Clear the image surface with Yellow color
graphic.clear(com.aspose.imaging.Color.getYellow());
// Draw a dotted ellipse shape by specifying the Pen object having red
// color and a surrounding Rectangle
graphic.drawEllipse(new Pen(com.aspose.imaging.Color.getRed()),
new com.aspose.imaging.Rectangle(30, 10, 40, 80));
// Draw a continuous ellipse shape by specifying the Pen object having
// solid brush with blue color and a surrounding Rectangle
graphic.drawEllipse(new Pen(new com.aspose.imaging.brushes.SolidBrush(com.aspose.imaging.Color.getBlue())),
new com.aspose.imaging.Rectangle(10, 30, 80, 40));
// Save all changes.
image.save(dataDir + "DrawingEllipse_out.bmp");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
com.aspose.imaging.imageoptions.BmpOptions bmpCreateOptions = new com.aspose.imaging.imageoptions.BmpOptions();
bmpCreateOptions.setBitsPerPixel(32);
// Define the source property for the instance of BmpOptions
bmpCreateOptions.setSource(
new com.aspose.imaging.sources.StreamSource(new java.io.ByteArrayInputStream(new byte[100 * 100 * 4])));
// Creates an instance of Image and call create method by passing the
// bmpCreateOptions object
com.aspose.imaging.Image image = com.aspose.imaging.Image.create(bmpCreateOptions, 100, 100);
// Create and initialize an instance of Graphics class
com.aspose.imaging.Graphics graphic = new com.aspose.imaging.Graphics(image);
// Clear the image surface with Yellow color
graphic.clear(com.aspose.imaging.Color.getYellow());
// Draw a dotted line by specifying the Pen object having blue color and
// co-ordinate Points
graphic.drawLine(new Pen(com.aspose.imaging.Color.getBlue()), 9, 9, 90, 90);
graphic.drawLine(new Pen(com.aspose.imaging.Color.getBlue()), 9, 90, 90, 9);
// Draw a continuous line by specifying the Pen object having Solid
// Brush with red color and two point structures
graphic.drawLine(new Pen(new com.aspose.imaging.brushes.SolidBrush(com.aspose.imaging.Color.getRed())),
new com.aspose.imaging.Point(9, 9), new com.aspose.imaging.Point(9, 90));
// Draw a continuous line by specifying the Pen object having Solid
// Brush with aqua color and two point structures
graphic.drawLine(new Pen(new com.aspose.imaging.brushes.SolidBrush(com.aspose.imaging.Color.getAqua())),
new com.aspose.imaging.Point(9, 90), new com.aspose.imaging.Point(90, 90));
// Draw a continuous line by specifying the Pen object having Solid
// Brush with black color and two point structures
graphic.drawLine(new Pen(new com.aspose.imaging.brushes.SolidBrush(com.aspose.imaging.Color.getBlack())),
new com.aspose.imaging.Point(90, 90), new com.aspose.imaging.Point(90, 9));
// Draw a continuous line by specifying the Pen object having Solid
// Brush with white color and two point structures
graphic.drawLine(new Pen(new com.aspose.imaging.brushes.SolidBrush(com.aspose.imaging.Color.getWhite())),
new com.aspose.imaging.Point(90, 9), new com.aspose.imaging.Point(9, 9));
// Save all changes.
image.save(dataDir + "DrawingLines_out.bmp");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Creates an instance of BmpOptions and set its various properties
com.aspose.imaging.imageoptions.BmpOptions bmpCreateOptions = new com.aspose.imaging.imageoptions.BmpOptions();
bmpCreateOptions.setBitsPerPixel(32);
// Define the source property for the instance of BmpOptions
bmpCreateOptions.setSource(
new com.aspose.imaging.sources.StreamSource(new java.io.ByteArrayInputStream(new byte[100 * 100 * 4])));
// Creates an instance of Image and call Create method by passing the
// bmpCreateOptionsobject
com.aspose.imaging.Image image = com.aspose.imaging.Image.create(bmpCreateOptions, 100, 100);
// Create and initialize an instance of Graphics class
com.aspose.imaging.Graphics graphic = new com.aspose.imaging.Graphics(image);
// Clear the image surface with Yellow color
graphic.clear(com.aspose.imaging.Color.getYellow());
// Draw a dotted rectangle shape by specifying the Pen object having red
// color and a rectangle structure
graphic.drawRectangle(new Pen(com.aspose.imaging.Color.getRed()),
new com.aspose.imaging.Rectangle(30, 10, 40, 80));
// Draw a continuous rectangle shape by specifying the Pen object having
// solid brush with blue color and a rectangle structure
graphic.drawRectangle(new Pen(new com.aspose.imaging.brushes.SolidBrush(com.aspose.imaging.Color.getBlue())),
new com.aspose.imaging.Rectangle(10, 30, 80, 40));
// Save all changes.
image.save(dataDir + "DrawingRectangle_out.bmp");
// The path to the documents directory.
String dataDir = "dataDir/";
//Create an instance of BmpCreateOptions and set its various properties
try (com.aspose.imaging.imageoptions.BmpOptions createOptions = new com.aspose.imaging.imageoptions.BmpOptions())
{
createOptions.setBitsPerPixel(24);
//Create an instance of FileCreateSource and assign it to Source property
createOptions.setSource(new com.aspose.imaging.sources.FileCreateSource(dataDir + "sample.bmp", false));
//Create an instance of Image
try (com.aspose.imaging.Image image = com.aspose.imaging.Image.create(createOptions, 500, 500))
{
//Create and initialize an instance of Graphics
com.aspose.imaging.Graphics graphics = new com.aspose.imaging.Graphics(image);
//Clear the image surface with white color
graphics.clear(Color.getWhite());
//Create and initialize a Pen object with blue color
com.aspose.imaging.Pen pen = new com.aspose.imaging.Pen(com.aspose.imaging.Color.getBlue());
//Draw Ellipse by defining the bounding rectangle of width 150 and height 100
graphics.drawEllipse(pen, new com.aspose.imaging.Rectangle(10, 10, 150, 100));
try (LinearGradientBrush linearGradientBrush = new LinearGradientBrush(image.getBounds(), Color.getRed(), Color.getWhite(), 45f))
{
graphics.fillPolygon(linearGradientBrush, new Point[] { new Point(200, 200), new Point(400, 200), new Point(250, 350) });
}
// Save all changes.
image.save();
}
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//Create an instance of BmpCreateOptions and set its various properties
com.aspose.imaging.imageoptions.BmpOptions createOptions = new com.aspose.imaging.imageoptions.BmpOptions();
createOptions.setBitsPerPixel(24);
//Create an instance of FileCreateSource and assign it to Source property
createOptions.setSource(new com.aspose.imaging.sources.FileCreateSource(dataDir + "sample.bmp",false));
//Create an instance of Image
com.aspose.imaging.Image image = com.aspose.imaging.Image.create(createOptions,500,500);
//Create and initialize an instance of Graphics
com.aspose.imaging.Graphics graphics = new com.aspose.imaging.Graphics(image);
//Clear the image surface with white color
graphics.clear(Color.getWhite());
//Create an instance of GraphicsPath
com.aspose.imaging.GraphicsPath graphicspath = new com.aspose.imaging.GraphicsPath();
//Create an instance of Figure
com.aspose.imaging.Figure figure = new com.aspose.imaging.Figure();
//Add Arc shape to the figure by defining boundary Rectangle
figure.addShape(new com.aspose.imaging.shapes.ArcShape(new RectangleF(10, 10, 300, 300), 0, 45));
//Add Arc Polygon shape to the figure by defining boundary Rectangle
figure.addShape(new com.aspose.imaging.shapes.PolygonShape(new PointF[]{new PointF(150, 10), new PointF(150, 200), new PointF(250, 300), new PointF(350, 400)}, true));
//Add Arc Polygon shape to the figure by defining boundary Rectangle
figure.addShape(new com.aspose.imaging.shapes.RectangleShape(new RectangleF(new PointF(250, 250), new SizeF(200, 200))));
//Add figures to the GraphicsPath object
graphicspath.addFigures(new Figure[]{ figure});
//Draw Path
graphics.drawPath(new Pen(com.aspose.imaging.Color.getBlack(), 2), graphicspath);
//Create an instance of HatchBrush and set its properties
com.aspose.imaging.brushes.HatchBrush hatchbrush = new com.aspose.imaging.brushes.HatchBrush();
hatchbrush.setBackgroundColor( com.aspose.imaging.Color.getBrown()); hatchbrush.setForegroundColor ( com.aspose.imaging.Color.getBlue());
hatchbrush.setHatchStyle (HatchStyle.Vertical);
//Fill path by supplying the brush and GraphicsPath objects
graphics.fillPath(hatchbrush, graphicspath);
// Save the final image.
image.save();
// Display Status.
System.out.println("Processing completed successfully!");
String dir = "images/";
RasterImage imageToDraw = (RasterImage)Image.load(dir + "asposenet_220_src01.png");
try
{
// Load the image for drawing on it (drawing surface)
EmfImage canvasImage = (EmfImage)Image.load(dir + "input.emf");
try
{
EmfRecorderGraphics2D graphics = EmfRecorderGraphics2D.fromEmfImage(canvasImage);
// Draw a rectagular part of the raster image within the specified bounds of the vector image (drawing surface).
// Note that because the source size is not equal to the destination one, the drawn image is stretched horizontally and vertically.
graphics.drawImage(
imageToDraw,
new Rectangle(67, 67, canvasImage.getWidth(), canvasImage.getHeight()),
new Rectangle(0, 0, imageToDraw.getWidth(), imageToDraw.getHeight()),
GraphicsUnit.Pixel);
// Save the result image
EmfImage resultImage = graphics.endRecording();
try
{
resultImage.save(dir + "input.DrawImage.emf");
}
finally
{
resultImage.close();
}
}
finally
{
canvasImage.close();
}
}
finally
{
imageToDraw.close();
}
String dir = "images/";
RasterImage imageToDraw = (RasterImage)Image.load(dir + "asposenet_220_src01.png");
try
{
// Load the image for drawing on it (drawing surface)
SvgImage canvasImage = (SvgImage )Image.load(dir + "asposenet_220_src02.svg");
try
{
SvgGraphics2D graphics = new SvgGraphics2D(canvasImage);
// Draw a rectagular part of the raster image within the specified bounds of the vector image (drawing surface).
// Note that because the source size is not equal to the destination one, the drawn image is stretched horizontally and vertically.
graphics.drawImage(
new Rectangle(0, 0, imageToDraw.getWidth(), imageToDraw.getHeight()),
new Rectangle(67, 67, imageToDraw.getWidth(), imageToDraw.getHeight()),
imageToDraw);
// Save the result image
SvgImage resultImage = graphics.endRecording();
try
{
resultImage.save(dir + "asposenet_220_src02.DrawImage.svg");
}
finally
{
resultImage.close();
}
}
finally
{
canvasImage.close();
}
}
finally
{
imageToDraw.close();
}
String dir = "images/";
// Load the image to be drawn
RasterImage imageToDraw = (RasterImage)Image.load(dir + "asposenet_220_src01.png");
try
{
// Load the image for drawing on it (drawing surface)
WmfImage canvasImage = (WmfImage)Image.load(dir + "asposenet_222_wmf_200.wmf");
try
{
WmfRecorderGraphics2D graphics = WmfRecorderGraphics2D.fromWmfImage(canvasImage);
// Draw a rectagular part of the raster image within the specified bounds of the vector image (drawing surface).
// Note that because the source size is not equal to the destination one, the drawn image is stretched horizontally and vertically.
graphics.drawImage(
imageToDraw,
new Rectangle(67, 67, canvasImage.getWidth(), canvasImage.getHeight()),
new Rectangle(0, 0, imageToDraw.getWidth(), imageToDraw.getHeight()),
GraphicsUnit.Pixel);
// Save the result image
WmfImage resultImage = graphics.endRecording();
try
{
resultImage.save(dir + "asposenet_222_wmf_200.DrawImage.wmf");
}
finally
{
resultImage.close();
}
}
finally
{
canvasImage.close();
}
}
finally
{
imageToDraw.close();
}
String dir = "images/";
try (ByteArrayOutputStream drawnImageStream = new ByteArrayOutputStream())
{
// First, rasterize Svg to Png and write the result to a stream.
try (SvgImage svgImage = (SvgImage)Image.load(dir + "asposenet_220_src02.svg"))
{
SvgRasterizationOptions rasterizationOptions = new SvgRasterizationOptions();
rasterizationOptions.setPageSize(Size.to_SizeF(svgImage.getSize()));
PngOptions saveOptions = new PngOptions();
saveOptions.setVectorRasterizationOptions(rasterizationOptions);
svgImage.save(drawnImageStream, saveOptions);
// Now load a Png image from stream for further drawing.
try (RasterImage imageToDraw = (RasterImage)Image.load(new ByteArrayInputStream(drawnImageStream.toByteArray())))
{
// Drawing on the existing Svg image.
SvgGraphics2D graphics = new SvgGraphics2D(svgImage);
// Scale down the entire drawn image by 2 times and draw it to the center of the drawing surface.
int width = imageToDraw.getWidth() / 2;
int height = imageToDraw.getHeight() / 2;
Point origin = new Point((svgImage.getWidth() - width) / 2, (svgImage.getHeight() - height) / 2);
Size size = new Size(width, height);
graphics.drawImage(imageToDraw, origin, size);
// Save the result image
SvgImage resultImage = graphics.endRecording();
try
{
resultImage.save(dir + "asposenet_220_src02.DrawVectorImage.svg");
}
finally
{
resultImage.close();
}
}
}
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
PsdImage image = (PsdImage)Image.load(dataDir+"input.psd");
try
{
image.save("NoFont.psd");
}
finally
{
image.dispose();
}
System.out.println("You have 2 minutes to install the font");
Thread.sleep(2 * 60 * 1000);
OpenTypeFontsCache.updateCache();
image = (PsdImage)Image.load("input.psd");
try
{
image.save("HasFont.psd");
}
finally
{
image.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String path = dataDir + "aspose-logo.jpg";
com.aspose.imaging.RasterImage image = (com.aspose.imaging.RasterImage) Image.load(path);
try {
// gets the date from [FileInfo]
String modifyDate = image.getModifyDate(true).toString();
System.out.format("Last modify date using FileInfo: %s\n", modifyDate);
// gets the date from XMP metadata of [FileInfo] as long as it's not
// default case
modifyDate = image.getModifyDate(false).toString();
System.out.format("Last modify date using info from FileInfo and XMP metadata: %s\n", modifyDate);
} finally {
image.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Sets the maximum allowed pixel difference. If greater than zero, lossy compression will be used.
// Recommended value for optimal lossy compression is 80. 30 is very light compression, 200 is heavy.
com.aspose.imaging.Image image = com.aspose.imaging.Image.load(dataDir + "aspose-logo.gif");
GifOptions gifExport = new GifOptions();
gifExport.setMaxDiff(80);
image.save(dataDir+"anim_lossy-80.gif", gifExport);
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String fileName = "testReplacementNotAvailableFonts.psd";
PsdImage image = (PsdImage)Image.load(fileName, new PsdLoadOptions(){{ setDefaultReplacementFont ("Arial"); }});
try
{
image.save("result.png", new PngOptions() {{ setColorType(PngColorType.TruecolorWithAlpha); }});
}
finally
{
image.dispose();
}
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(SupportOfDIB.class) + "images/";
Image image = Image.load(dataDir + "sample.dib");
try {
System.out.println(FileFormat.toString(FileFormat.class, image.getFileFormat())); // Output is "Bmp"
image.save(dataDir + "sample.png", new PngOptions());
} finally {
image.close();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//String dir = "C:\\Temp\\Errors\\";
String dataDir = Utils.getSharedDataDir(SupportForInterruptMonitor.class) + "InterruptMonitor/";
ImageOptionsBase saveOptions = new PngOptions();
InterruptMonitor monitor = new InterruptMonitor();
SaveImageWorker worker = new SaveImageWorker(dataDir + "big.jpg", dataDir + "big_out.png", saveOptions, monitor);
Thread thread = new Thread(worker);
try
{
thread.start();
// The timeout should be less than the time required for full image conversion (without interruption).
Thread.sleep(3000);
// Interrupt the process
System.out.format("Interrupting the save thread #%d at %s\n", thread.getId(), new Date().toString());
monitor.interrupt();
// Wait for interruption...
thread.join();
}
finally
{
// If the file to be deleted does not exist, no exception is thrown.
File f = new File(dataDir + "big_out.png");
f.delete();
}
}
/**
* Initiates image conversion and waits for its interruption.
*/
private class SaveImageWorker implements Runnable
{
/**
* The path to the input image.
*/
private final String inputPath;
/**
* The path to the output image.
*/
private final String outputPath;
/**
* The interrupt monitor.
*/
private final InterruptMonitor monitor;
/**
* The save options.
*/
private final ImageOptionsBase saveOptions;
/**
* Initializes a new instance of the SaveImageWorker class.
* @param inputPath The path to the input image.
* @param outputPath The path to the output image.
* @param saveOptions The save options.
* @param monitor The interrupt monitor.
*/
public SaveImageWorker(String inputPath, String outputPath, ImageOptionsBase saveOptions, InterruptMonitor monitor)
{
this.inputPath = inputPath;
this.outputPath = outputPath;
this.saveOptions = saveOptions;
this.monitor = monitor;
}
/**
* Tries to convert image from one format to another. Handles interruption.
*/
public void run()
{
Image image = Image.load(this.inputPath);
try
{
InterruptMonitor.setThreadLocalInstance(this.monitor);
try
{
image.save(this.outputPath, this.saveOptions);
}
catch (OperationInterruptedException e)
{
System.out.format("The save thread #%d finishes at %s\n", Thread.currentThread().getId(), new Date().toString());
System.out.println(e);
}
catch (Exception e)
{
System.out.println(e);
}
finally
{
InterruptMonitor.setThreadLocalInstance(null);
}
}
finally
{
image.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//Declare variables to store file path for input image.
String sourceFiles = "Path_to_source_folder\\Source\\HDR - 3c.dng";
// Create an instance of Image class and load an exiting DNG file.
// Convert the image to DngImage object.
com.aspose.imaging.fileformats.dng.DngImage objimage = (com.aspose.imaging.fileformats.dng.DngImage)
com.aspose.imaging.Image.load(sourceFiles);
System.out.println("Camera model:" + objimage.getImgData().getImageDataParameters().getModel());
System.out.println("Camera manufacturer:" + objimage.getImgData().getImageDataParameters().getCameraManufacturer());
System.out.println("Software:" + objimage.getImgData().getImageDataParameters().getSoftware());
System.out.println("Colors count:" + objimage.getImgData().getImageDataParameters().getColorsCount());
System.out.println("Artist:" + objimage.getImgData().getImageOtherParameters().getArtist());
System.out.println("Aperture:" + objimage.getImgData().getImageOtherParameters().getAperture());
System.out.println("Focal length:" + objimage.getImgData().getImageOtherParameters().getFocalLength());
System.out.println("Iso speed:" + objimage.getImgData().getImageOtherParameters().getIsoSpeed());
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//Declare variables to store file paths for input and output images.
String sourceFiles = "Path_to_source_folder\\Source\\HDR - 3c.dng";
String destPath = "Path_to_results_folder\\Results\\result.jpg";
// Create an instance of Image class and load an exiting DNG file.
// Convert the image to DngImage object.
com.aspose.imaging.fileformats.dng.DngImage objimage = (com.aspose.imaging.fileformats.dng.DngImage)
com.aspose.imaging.Image.load(sourceFiles);
// Create an instance of JpegOptions class.
// convert and save to disk in Jpeg file format.
objimage.save(destPath, new com.aspose.imaging.imageoptions.JpegOptions());
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Create an instance of JpegImage to store the thumbnail
JpegImage thumbnailImage = new JpegImage(100, 100);
// Create another instance of JpegImage as primary image
JpegImage image = new JpegImage(1000, 1000);
// Set the ExifData value as new JpegExifData
image.setExifData(new JpegExifData());
// Store the thumbnail in the Exif segment
image.getExifData().setThumbnail(thumbnailImage);
// Save the resultant image
image.save(dataDir + "AddThumbnailtoEXIFSegment_out.jpg");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//Create an instance of JpegImage to store the thumbnail
JpegImage thumbnailImage = new JpegImage(100, 100);
//Create another instance of JpegImage as primary image
JpegImage image = new JpegImage(1000, 1000);
//Set the Jfif value as new JFIFData
image.setJfif( new JFIFData());
//Store the thumbnail in the Jfif segment
image.getJfif().setThumbnail(thumbnailImage);
//Save the resultant image
image.save(dataDir + "AddThumbnailtoJFIFSegment_out.jpg");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//Load a Jpeg image from file path location or stream
JpegImage image = (JpegImage)Image.load(dataDir + "aspose-logo.jpg");
//Perform the automatic rotation on the image depending on the orientation data stored in the EXIF
image.autoRotate();
//Save the result on disc or stream
image.save(dataDir + "AutoCorrectOrientationOfJPEGImages_out.jpg");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
Image original = Image.load(dataDir+"ColorGif.gif");
try
{
JpegOptions jpegOptions = new JpegOptions()
{{
setColorType(JpegCompressionColorMode.Grayscale);
setCompressionType(JpegCompressionMode.Progressive);
}};
original.save("result.jpg", jpegOptions);
}
finally
{
original.dispose();
}
}
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(ConvertTIFFToJPEG.class) + "ManipulatingJPEGImages/";
TiffImage tiffImage = (TiffImage)Image.load(dataDir + "source2.tif");
try
{
int i = 0;
for (TiffFrame tiffFrame : tiffImage.getFrames())
{
JpegOptions saveOptions = new JpegOptions();
saveOptions.setResolutionSettings(new ResolutionSetting(tiffFrame.getHorizontalResolution(), tiffFrame.getVerticalResolution()));
TiffOptions frameOptions = tiffFrame.getFrameOptions();
if (frameOptions != null)
{
// Set the resolution unit explicitly.
switch (frameOptions.getResolutionUnit())
{
case TiffResolutionUnits.None:
saveOptions.setResolutionUnit(ResolutionUnit.None);
break;
case TiffResolutionUnits.Inch:
saveOptions.setResolutionUnit(ResolutionUnit.Inch);
break;
case TiffResolutionUnits.Centimeter:
saveOptions.setResolutionUnit(ResolutionUnit.Cm);
break;
default:
throw new RuntimeException("Current resolution unit is unsupported!");
}
}
String fileName = "source2.tif.frame." + (i++) + "."
+ ResolutionUnit.toString(ResolutionUnit.class, saveOptions.getResolutionUnit()) + ".jpg";
tiffFrame.save(dataDir + fileName, saveOptions);
}
}
finally
{
tiffImage.close();
}
// 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");
// Initialize an object of ExifData and fill it will image's EXIF
// information
ExifData exif = ((JpegImage) image).getExifData();
// Check if image has any EXIF entries defined
if (exif != null) {
// Display a few EXIF entries
System.out.println("Exif WhiteBalance: " + exif.getWhiteBalance());
System.out.println("Exif PixelXDimension: " + exif.getPixelXDimension());
System.out.println("Exif PixelYDimension: " + exif.getPixelYDimension());
System.out.println("Exif ISOSpeed: " + exif.getISOSpeed());
System.out.println("Exif BodySerialNumber: " + exif.getBodySerialNumber());
System.out.println("Exif CameraOwnerName: " + exif.getCameraOwnerName());
System.out.println("Exif ColorSpace: " + exif.getColorSpace());
System.out.println("Exif Contrast: " + exif.getContrast());
System.out.println("Exif CustomRendered: " + exif.getCustomRendered());
System.out.println("Exif DateTimeDigitized: " + exif.getDateTimeDigitized());
System.out.println("Exif DateTimeOriginal: " + exif.getDateTimeOriginal());
System.out.println("Exif ExposureMode: " + exif.getExposureMode());
System.out.println("Exif ExposureProgram: " + exif.getExposureProgram());
System.out.println("Exif Flash: " + exif.getFlash());
System.out.println("Exif FocalLengthIn35MmFilm: " + exif.getFocalLengthIn35MmFilm());
System.out.println("Exif FocalPlaneResolutionUnit: " + exif.getFocalPlaneResolutionUnit());
System.out.println("Exif GainControl: " + exif.getGainControl());
System.out.println("Exif ImageUniqueID: " + exif.getImageUniqueID());
System.out.println("Exif Sharpness: " + exif.getSharpness());
System.out.println("Exif MeteringMode: " + exif.getMeteringMode());
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load the image in an instance of JpegImage
JpegImage image = (JpegImage) Image.load(dataDir + "aspose-logo.jpg");
if (image.getExifData() != null) {
// Get the image thumbnail information and save it in an instance of
// JpegImage
JpegImage thumbnail = (JpegImage) image.getExifData().getThumbnail();
// Save the thumbnail to disk with a new name
thumbnail.save(dataDir + "ReadJpegEXIFTags_out.jpg");
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load the image in an instance of JpegImage
JpegImage image = (JpegImage) Image.load(dataDir + "aspose-logo.jpg");
// Get the image thumbnail information and save it in an instance of
// JpegImage
JpegImage thumbnail = (JpegImage) image.getExifData().getThumbnail();
// Retrieve the thumbnail bitmap information/Pixels in an array of type
// Color
Color[] pixels = thumbnail.loadPixels(new Rectangle(0, 0, thumbnail.getWidth(), thumbnail.getHeight()));
// To save the thumbnail as BMP image, create an instance of BmpOptions
BmpOptions bmpOptions = new BmpOptions();
// Set file source in which the results will be stores; last Boolean
// parameter denotes isTemporal
bmpOptions.setSource(new FileCreateSource(dataDir + "RetrieveThumbnailBitmapInformation_out.jpg", false));
// Create a BmpImage while using the instance of BmpOptions and
// providing resultant dimensions
BmpImage bmpImage = (BmpImage) Image.create(bmpOptions, thumbnail.getWidth(), thumbnail.getHeight());
// Copy the thumbnail pixels onto the newly created canvas
bmpImage.savePixels(bmpImage.getBounds(), pixels);
// Save the results
bmpImage.save();
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
int bpp = 2; // Set 2 bits per sample to see the difference in size and quality
// The origin PNG with 8 bits per sample
String originPngFileName = "lena24b.png";
// The output JPEG-LS with 2 bits per sample.
String outputJpegFileName = "lena24b " + bpp + "-bit Gold.jls";
PngImage pngImage = (PngImage)Image.load(originPngFileName);
try
{
JpegOptions jpegOptions = new JpegOptions();
jpegOptions.setBitsPerChannel((byte)bpp);
jpegOptions.setCompressionType(JpegCompressionMode.JpegLs);
pngImage.save(outputJpegFileName, jpegOptions);
}
finally
{
pngImage.dispose();
}
// The output PNG is produced from JPEG-LS to check image visually.
String outputPngFileName = "lena24b " + bpp + "-bit Gold.png";
JpegImage jpegImage = (JpegImage)Image.load(outputJpegFileName);
try
{
jpegImage.save(outputPngFileName, new PngOptions());
}
finally
{
jpegImage.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// The path to the documents directory.
ByteArrayOutputStream jpegStream_cmyk = new ByteArrayOutputStream();
ByteArrayOutputStream jpegStream_ycck = new ByteArrayOutputStream();
// Save to JPEG Lossless CMYK
JpegImage image = (JpegImage)Image.load("056.jpg");
try
{
JpegOptions options = new JpegOptions();
options.setCompressionType(JpegCompressionMode.Lossless);
// The default profiles will be used.
options.setRgbColorProfile(null);
options.setCmykColorProfile(null);
// Save to Cmyk
options.setColorType(JpegCompressionColorMode.Cmyk);
image.save(jpegStream_cmyk, options);
// Save to Ycck
options.setColorType(JpegCompressionColorMode.Ycck);
image.save(jpegStream_ycck, options);
options.dispose();
}
finally
{
image.dispose();
}
// Load from JPEG Lossless CMYK
image = (JpegImage)Image.load(new ByteArrayInputStream(jpegStream_cmyk.toByteArray()));
try
{
image.save("056_cmyk.png", new PngOptions());
}
finally
{
image.dispose();
}
// Load from JPEG Lossless Ycck
image = (JpegImage)Image.load(new ByteArrayInputStream(jpegStream_ycck.toByteArray()));
try
{
image.save("056_ycck.png", new PngOptions());
}
finally
{
image.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String sourceJpegFileName = "lena24b.jls";
String outputPngFileName = "lena24b.png";
String outputPngRectFileName = "lena24b_rect.png";
// Decoding
JpegImage jpegImage = (JpegImage)Image.load(sourceJpegFileName);
try
{
JpegOptions jpegOptions = jpegImage.getJpegOptions();
// You can read new options:
System.out.format("Compression type: %s\n", JpegCompressionMode.getName(JpegCompressionMode.class, jpegOptions.getCompressionType()));
System.out.format("Allowed lossy error (NEAR): %d\n", jpegOptions.getJpegLsAllowedLossyError());
System.out.format("Interleaved mode (ILV): %s\n", JpegLsInterleaveMode.getName(JpegLsInterleaveMode.class, jpegOptions.getJpegLsInterleaveMode()));
System.out.format("Horizontal sampling: %s\n", arrayToString(jpegOptions.getHorizontalSampling()));
System.out.format("Vertical sampling: %s\n", arrayToString(jpegOptions.getVerticalSampling()));
// Save the original JPEG-LS image to PNG.
jpegImage.save(outputPngFileName, new PngOptions());
// Save the bottom-right quarter of the original JPEG-LS to PNG
Rectangle quarter = new Rectangle(jpegImage.getWidth() / 2, jpegImage.getHeight() / 2, jpegImage.getWidth() / 2, jpegImage.getHeight() / 2);
jpegImage.save(outputPngRectFileName, new PngOptions(), quarter);
}
finally
{
jpegImage.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
ByteArrayOutputStream jpegLsStream = new ByteArrayOutputStream();
// Save to CMYK JPEG-LS
JpegImage image = (JpegImage) Image.load("056.jpg");
try
{
JpegOptions options = new JpegOptions();
//Just replace one line given below in example to use YCCK instead of CMYK
//options.setColorType(JpegCompressionColorMode.Ycck);
options.setColorType(JpegCompressionColorMode.Cmyk);
options.setCompressionType(JpegCompressionMode.JpegLs);
// The default profiles will be used.
options.setRgbColorProfile(null);
options.setCmykColorProfile(null);
image.save(jpegLsStream, options);
}
finally
{
image.dispose();
}
// Load from CMYK JPEG-LS
image = (JpegImage) Image.load(new ByteArrayInputStream(jpegLsStream.toByteArray()));
try
{
image.save("056_cmyk.png", new PngOptions());
}
finally
{
image.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load an image using the factory method load exposed by Image class
Image image = Image.load(dataDir + "aspose-logo.jpg");
// Initialize an object of ExifData and fill it will image's EXIF
// information
ExifData exif = ((JpegImage) image).getExifData();
// Set Lens Make information
exif.setLensMake("Sony");
// Set WhiteBalance information
exif.setWhiteBalance(com.aspose.imaging.exif.enums.ExifWhiteBalance.Auto);
// Set that Flash was fires
exif.setFlash(com.aspose.imaging.exif.enums.ExifFlash.Fired);
// Save the changes to the original image
image.save();
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
com.aspose.imaging.fileformats.png.PngImage png = (com.aspose.imaging.fileformats.png.PngImage) com.aspose.imaging.Image
.load(dataDir + "aspose_logo.png");
// Create an instance of PngOptions
com.aspose.imaging.imageoptions.PngOptions options = new com.aspose.imaging.imageoptions.PngOptions();
// Set the PNG filter method
options.setFilterType(com.aspose.imaging.fileformats.png.PngFilterType.Paeth);
// Save changes to the disc
png.save(dataDir + "ApplyFilterMethod_out.jpg", options);
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Create an instance of Image class and load a PNG image
com.aspose.imaging.Image img = com.aspose.imaging.Image.load(dataDir + "aspose_logo.png");
// Create an instance of RasterImage and get the pixels array by calling
// method LoadArgb32Pixels.
com.aspose.imaging.RasterImage rasterImg = (com.aspose.imaging.RasterImage) img;
int[] pixels = rasterImg.loadArgb32Pixels(img.getBounds());
// Iterate through the pixel array.
for (int i = 0; i < pixels.length; i++) {
// Check the pixel information that if it is a transparent color
// pixel
if (pixels[i] == rasterImg.getTransparentColor().toArgb()) {
// Change the pixel color to white
pixels[i] = com.aspose.imaging.Color.getWhite().toArgb();
}
}
// Replace the pixel array into the image.
rasterImg.saveArgb32Pixels(img.getBounds(), pixels);
// Save the updated image to disk.
rasterImg.save(dataDir + "ChangeBackgroundColor_out.png");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load an image from file (or stream)
Image image = Image.load(dataDir + "aspose_logo.png");
// Loop over possible CompressionLevel range
for (int i = 0; i <= 9; i++) {
// Create an instance of PngOptions for each resultant PNG
PngOptions options = new PngOptions();
// Set CompressionLevel
options.setCompressionLevel(i);
// Save result on disk (or stream)
image.save("CompressingFiles_out" + i + ".png", options);
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load the source image (any format) in an instance of RasterImage
RasterImage image = (RasterImage) Image.load(dataDir + "aspose-logo.jpg");
// Set the background color for the image
image.setBackgroundColor(Color.getWhite());
// Set the transparent color for the image
image.setTransparentColor(Color.getBlack());
// Set the HasTransparentColor & HasBackgroundColor properties to true
image.setBackgroundColor(true);
image.setTransparentColor(true);
// Save the image on disc in PNG format
image.save(dataDir + "ConvertanyLoadedImageDirectlyToPNGformat_out.jpg", new PngOptions());
String dataDir = Utils.getSharedDataDir(ReadLargePNGFile.class) + "ManipulatingPNGImages/";
Image image = Image.load(dataDir + "halfGigImage.png");
// Create an instance of JpegOptions
JpegOptions options = new JpegOptions();
image.save(dataDir + "halfGigImage.jpg", options);
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load an existing PNG image
PngImage pngImage = (PngImage) Image.load(dataDir + "aspose_logo.png");
// Create an instance of PngOptions
PngOptions options = new PngOptions();
// Set the desired ColorType
options.setColorType(PngColorType.Grayscale);
// Set the BitDepth according to the specified ColorType
options.setBitDepth((byte) 1);
// Save changes to the disc
pngImage.save(dataDir + "SpecifyBitDepth_out.jpg", options);
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Initialize variables to hold width & height values
int width = 0;
int height = 0;
// Initialize an array of type Color to hold the pixel data
Color[] pixels = null;
// Create an instance of RasterImage and load a BMP image
RasterImage raster = (RasterImage) Image.load(dataDir + "aspose-logo.jpg");
// Store the width & height in variables for later use
width = raster.getWidth();
height = raster.getHeight();
// Load the pixels of RasterImage into the array of type Color
pixels = raster.loadPixels(new Rectangle(0, 0, width, height));
// Create & initialize an instance of PngImage while specifying size and PngColorType
PngImage png = new PngImage(width, height, PngColorType.TruecolorWithAlpha);
// Save the previously loaded pixels on to the new PngImage
png.savePixels(new Rectangle(0, 0, width, height), pixels);
// Set TransparentColor property to specify which color to be rendered as transparent
png.setTransparentColor(Color.getBlack());
// Save the result on disc
png.save(dataDir + "SpecifyTransparency_out.jpg");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Create an instance of TiffOptions with CCITTFAX3 compression
TiffOptions outputSettings = new TiffOptions(TiffExpectedFormat.TiffCcittFax3);
// Set source for the result
outputSettings.setSource(new FileCreateSource(dataDir + "output.tiff", false));
// Declare Height and Width for the new TiffImage
final int newWidth = 500;
final int newHeight = 500;
// Create an instance of TiffImage using the object of TiffOptions and dimension
TiffImage tiffImage = (TiffImage) Image.create(outputSettings, newWidth, newHeight);
// Initialize a variable to keep track of frames in the TiffImage
int index = 0;
// Read all JPG files from any specified directory and iterate over the list
final File folder = new File("samples/");
for (final File fileEntry : folder.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".jpg");
}
})) {
// Load the image into an instance of RasterImage
RasterImage image = (RasterImage) Image.load(fileEntry.getAbsolutePath());
// Resize the image according to TiffImage dimensions
image.resize(newWidth, newHeight, ResizeType.NearestNeighbourResample);
// Get the active frame of TiffImage
TiffFrame frame = tiffImage.getActiveFrame();
// Save the RasterImage data onto TiffFrame
frame.savePixels(frame.getBounds(), image.loadPixels(image.getBounds()));
// Check if TiffImage already has a frame
if (index > 0) {
// Create a new TiffFrame according to the TiffOptions settings
frame = new TiffFrame(new TiffOptions(outputSettings), newWidth, newHeight);
// Add the newly created frame to the TiffImage
tiffImage.addFrame(frame);
}
index++;
}
// Save the changes to TiffImage
tiffImage.save();
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Create an instance of LoadOptions
LoadOptions loadOptions = new LoadOptions();
// Specify the DataRecoveryMode for the object of LoadOptions
loadOptions.setDataRecoveryMode(DataRecoveryMode.ConsistentRecover);
// Specify the DataBackgroundColor for the object of LoadOptions
loadOptions.setDataBackgroundColor(Color.getRed());
// Create an instance of Image and load a damaged image by passing the
// instance of LoadOptions
Image image = Image.load(dataDir + "DataRecovery_out.tif", loadOptions);
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
TiffImage multiImage = (TiffImage) Image.load(dataDir + "sample.tif");
TiffFrame[] frames = multiImage.getFrames();
int i = 0;
for (TiffFrame frame : frames) {
frame.save(dataDir + "ExtractTIFFFramestoOtherImageFormat_out" +i+ ".jpg", new JpegOptions());
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String dataDir = Utils.getSharedDataDir(MultipleImageToTiff.class) + "ManipulatingTIFFImages/";
//String path = @"C:\Imaging Data\IMG\";
int page = 0;
Image tempImage = com.aspose.imaging.Image.load(dataDir + "Image1.png");
int width = 500;
int height = 500;
width = tempImage.getWidth();
height = tempImage.getHeight();
com.aspose.imaging.imageoptions.TiffOptions tiffOptions = new com.aspose.imaging.imageoptions.TiffOptions(TiffExpectedFormat.Default);
tiffOptions.setSource(new com.aspose.imaging.sources.FileCreateSource(dataDir+"MultiPage.tiff", false));
try
( //Create an instance of Image and initialize it with instance of BmpOptions by calling Create method
TiffImage TiffImage = (TiffImage)com.aspose.imaging.Image.create(tiffOptions, width, height)) {
//do some image processing
File di = new File(dataDir);
String[] files = di.list(new FilenameFilter()
{
@Override
public boolean accept(File dir, String name)
{
return name.endsWith(".img");
}
});
int index = 0;
for (String file : files)
{
com.aspose.imaging.Image inputImage = com.aspose.imaging.Image.load(dataDir + File.separator + file);
try
{
inputImage.resize(width, height, ResizeType.NearestNeighbourResample);
// var frame = TiffImage.ActiveFrame;
if (index > 0)
{
TiffFrame newframe = new TiffFrame(tiffOptions, width, height);
TiffImage.addFrame(newframe);
int cnt = TiffImage.getFrames().length;
}
TiffFrame frame = TiffImage.getFrames()[index];
frame.savePixels(frame.getBounds(), ((RasterImage)inputImage).loadPixels(inputImage.getBounds()));
index += 1;
}
finally
{
inputImage.close();
}
}
// save all changes
TiffImage.save(dataDir+"output.tiff");
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
public static void main(String... args) throws Exception {
String dataDir = Utils.getSharedDataDir(SupportTiffDeflate.class) + "ManipulatingTIFFImages/";
String inputFile = "C:\\Temp\\Errors\\Alpha.png";
String outputFileTiff = "C:\\Temp\\Alpha.tiff";
String outputFilePng = "C:\\Temp\\Alpha1.png";
Image image = Image.load(inputFile);
try
{
TiffOptions options = new TiffOptions(TiffExpectedFormat.TiffDeflateRgba);
image.save(outputFileTiff, options);
}
finally
{
image.dispose();
}
image = Image.load(outputFileTiff);
try
{
Assert.assertEquals(((RasterImage)image).hasAlpha(), true);
PngOptions options = new PngOptions();
options.setColorType(PngColorType.TruecolorWithAlpha);
image.save(outputFilePng, options);
}
finally
{
image.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load an image through file path location or stream
Image image = Image.load(dataDir + "new.tiff");
// Create an instance of TiffOptions while specifying desired format. Passing TiffExpectedFormat.TiffJpegRGB will set the compression to Jpeg
// and BitsPerPixel according to the RGB color space
TiffOptions options = new TiffOptions(TiffExpectedFormat.TiffJpegRgb);
// Save the result in Tiff format RGB with Jpeg compression
image.save(dataDir + "TiffOptionsConfiguration_out.tiff", options);
// 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();
}
// 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));
// 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());
// 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();
}
}
// 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();
// 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);
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load an existing EMF file
Image image = Image.load(dataDir + "Picture1.emf", new MetafileLoadOptions(true));
try {
// Create an instance of EmfRasterizationOptions class and set
// different options
final EmfRasterizationOptions emfRasterizationOptions = new EmfRasterizationOptions();
emfRasterizationOptions.setBackgroundColor(Color.getWhite());
emfRasterizationOptions.setPageWidth(image.getWidth());
emfRasterizationOptions.setPageHeight(image.getHeight());
// call the save method and pass instance of SvgOptions class to
// convert it to SVG format.
image.save(dataDir + "ConvertEMFtoSVG_out.svg", new SvgOptions() {
{
setVectorRasterizationOptions(emfRasterizationOptions);
}
});
} finally {
image.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// List of existing EMF images.
String path = "";
String[] files = new String[] { "TestEmfRotatedText.emf", "TestEmfPlusFigures.emf", "TestEmfBezier.emf" };
// Loop for each file name.
for (String file : files)
{
// Input file name & path.
String filePath = path + "\\" + file;
// Load the EMF image as image and convert it to MetaImage object.
com.aspose.imaging.fileformats.emf.MetaImage image =
(com.aspose.imaging.fileformats.emf.MetaImage)com.aspose.imaging.Image.load(filePath, new com.aspose.imaging.imageloadoptions.MetafileLoadOptions(true));
try
{
// Convert the EMF image to WMF image by creating and passing WMF image options class object.
image.save(filePath + "_out.wmf", new com.aspose.imaging.imageoptions.WmfOptions());
}
finally
{
// clean the resources
image.dispose();
}
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
public static void main(String... args) throws Exception {
String dataDir = Utils.getSharedDataDir(CreateEMFMetaFileImage.class) + "metafile/";
new CreateEMFMetaFileImage().penAndMixedArcTests();
}
public void penAndMixedArcTests()
{
// EmfRecorderGraphics2D class provides you the frame or canvas to draw shapes on it.
// Create an instance of EmfRecorderGraphics2D class. The constructor takes in 3 parameters:
// 1. Instance of Imaging Rectangle class
// 2. Instance of Imaging Size class
// 3. Instance of Imaging Size class
EmfRecorderGraphics2D graphics = new EmfRecorderGraphics2D(new Rectangle(0, 0, 1000, 1000), new Size(1000, 1000)
, new Size(100, 100));
{
String dataDir = Utils.getSharedDataDir(CreateEMFMetaFileImage.class) + "metafile/";
// Create an instance of Imaging Pen class and mention its color.
Pen pen = new Pen(Color.getBisque().Clone());
// Draw a line by calling DrawLine method and passing x,y coordinates of 1st point and same for 2nd point along with color info as Pen.
graphics.drawLine(pen, 1, 1, 50, 50);
// Reset the Pen color.
pen = new Pen(Color.getBlueViolet().Clone(), 3);
// specify the end style of the line.
pen.setEndCap(LineCap.Round);
// Draw a line by calling DrawLine method and passing x,y coordinates of 1st point and same for 2nd point along with color infor as Pen and end style of line.
graphics.drawLine(pen, 15, 5, 50, 60);
// specify the end style of the line.
pen.setEndCap(LineCap.Square);
// Draw a line by calling DrawLine method.
graphics.drawLine(pen, 5, 10, 50, 10);
// specify the end style of the line.
pen.setEndCap(LineCap.Flat);
// Draw a line by calling DrawLine method.
graphics.drawLine(pen, new Point(5, 20), new Point(50, 20));
// Create an instance of HatchBrush class to define rectanglurar brush with with different settings.
HatchBrush hatchBrush = new com.aspose.imaging.brushes.HatchBrush();
hatchBrush.setBackgroundColor(Color.getAliceBlue().Clone());
hatchBrush.setForegroundColor(Color.getRed().Clone());
hatchBrush.setHatchStyle(HatchStyle.Cross);
pen = new Pen(hatchBrush, 7);
graphics.drawRectangle(pen, 50, 50, 20, 30);
graphics.setBackgroundMode(com.aspose.imaging.fileformats.emf.emf.consts.EmfBackgroundMode.OPAQUE);
graphics.drawLine(pen, 80, 50, 80, 80);
// Draw a line by calling DrawLine method and passing parameters.
pen = new Pen(new SolidBrush(Color.getAqua().Clone()), 3);
pen.setLineJoin(LineJoin.MiterClipped);
// Draw a polygon by calling DrawPolygon method and passing parameters with line join setting/style.
graphics.drawPolygon(pen, new Point[] { new Point(10, 20), new Point(12, 45), new Point(22, 48), new Point(48
, 36), new Point(30, 55) });
pen.setLineJoin(LineJoin.Bevel);
graphics.drawRectangle(pen, 50, 10, 10, 5);
pen.setLineJoin(LineJoin.Round);
graphics.drawRectangle(pen, 65, 10, 10, 5);
pen.setLineJoin(LineJoin.Miter);
graphics.drawRectangle(pen, 80, 10, 10, 5);
// Call EndRecording method to produce the final shape. EndRecording method will return the final shape as EmfImage.
// So create an instance of EmfImage class and initialize it with EmfImage returned by EndRecording method.
final EmfImage image = graphics.endRecording();
try /*JAVA: was using*/
{
test(image, dataDir + "Picture1.emf");
}
finally
{
if (image != null)
(image).dispose();
}
}
}
private void test(EmfImage image, String fileName)
{
// Create an instance of PdfOptions class.
PdfOptions options = new PdfOptions();
// Create an instance of EmfRasterizationOptions class and define different settings.
EmfRasterizationOptions rasterizationOptions = new EmfRasterizationOptions();
options.setVectorRasterizationOptions(rasterizationOptions);
rasterizationOptions.setPageSize(com.aspose.imaging.Size.to_SizeF(image.getSize()).Clone());
String outPath = fileName + "CreateEMFMetaFileImage_out.pdf";
// Call the save method to convert the EMF metafile image to PDF.
image.save(outPath, options);
}
// 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());
Image image = Image.load(dataDir + "picture1.emf");
try
{
final EmfRasterizationOptions emfRasterizationOptions = new EmfRasterizationOptions();
emfRasterizationOptions.setBackgroundColor(Color.getWhite());
emfRasterizationOptions.setPageWidth(image.getWidth());
emfRasterizationOptions.setPageHeight(image.getHeight());
image.save(dataDir + "ExportTextasShape_out.svg", new SvgOptions() {
{
setVectorRasterizationOptions(emfRasterizationOptions);
setTextAsShapes(true);
}
});
image.save(dataDir + "ExportTextasShape_text_out.svg", new SvgOptions() {
{
setVectorRasterizationOptions(emfRasterizationOptions);
setTextAsShapes(false);
}
});
} finally
{
image.close();
}
// 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);
}
// 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;
}
String dataDir = "dataDir/";
com.aspose.imaging.fileformats.emf.graphics.EmfRecorderGraphics2D graphics = new com.aspose.imaging.fileformats.emf.graphics.EmfRecorderGraphics2D(
new com.aspose.imaging.Rectangle(0, 0, 5000, 5000),
new com.aspose.imaging.Size(5000, 5000),
new com.aspose.imaging.Size(1000, 1000));
Font font = new Font("Arial", 10, FontStyle.Bold | FontStyle.Underline);
graphics.drawString(font.getName()+ " " + font.getSize() + " " + FontStyle.toString(FontStyle.class, font.getStyle()), font, Color.getBrown(), 10, 10);
graphics.drawString("some text", font, Color.getBrown(), 10, 30);
font = new Font("Arial", 24, FontStyle.Italic | FontStyle.Strikeout);
graphics.drawString(font.getName() + " " + font.getSize() + " " + FontStyle.toString(FontStyle.class, font.getStyle()), font, Color.getBrown(), 20, 50);
graphics.drawString("some text", font, Color.getBrown(), 20, 80);
EmfImage image = graphics.endRecording();
try
{
String path = dataDir + "Fonts.emf";
image.save(path, new EmfOptions());
}
finally
{
image.close();
}
String dataDir = "dataDir/";
String path = dataDir + "TestEmfPlusFigures.emf";
EmfImage image = (EmfImage)Image.load(path);
try
{
image.save(path + ".emf", new EmfOptions());
}
finally
{
image.close();
}
String dataDir = "dataDir/";
String path = dataDir + "TestEmfBezier.emf";
EmfImage image = (EmfImage)Image.load(path);
try
{
image.save(path + ".emf", new EmfOptions());
}
finally
{
image.close();
}
// 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);
}
// 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);
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
private static final String FontFolderName = "fonts";
private static final String OutFolderName = "Out\\";
private static final String SourceFolder = "C:\\Temp\\Errors\\6\\";
private static String OutFolder = SourceFolder + OutFolderName;
private static String FontFolder = OutFolder + "\\" + FontFolderName;
public void readFileWithEmbeddedFontsAndExportToPdf()
{
this.readAndExportToPdf("EmbeddedFonts.svg");
}
public void readFileWithExportedFontsAndExportToPdf()
{
this.readAndExportToPdf("ExportedFonts.svg");
}
public void saveWithEmbeddedFonts()
{
String[] files = new String[]
{
"exportedFonts.svg", // File with exported fonts
"embeddedFonts.svg", // File with embedded fonts
"mysvg.svg" // simple file
};
for (int i = 0; i < files.length; i++)
{
this.save(true, files[i], 0);
}
}
public void saveWithExportFonts()
{
String[] files = new String[]
{
"exportedFonts.svg", // File with exported fonts
"embeddedFonts.svg", // File with embedded fonts
"mysvg.svg" // simple file
};
int[] expectedFontsCount = new int[] {
4, 4, 1
} ;
for (int i = 0; i < files.length; i++)
{
this.save(false, files[i], expectedFontsCount[i]);
}
}
private void readAndExportToPdf(String inputFileName)
{
File f = new File(OutFolder);
if (!f.exists())
{
f.mkdir();
}
String inputFile = SourceFolder + inputFileName;
String outFile = OutFolder + "\\" + inputFileName + ".pdf";
final Image image = Image.load(inputFile);
try
{
image.save(outFile,
new PdfOptions()
{{
setVectorRasterizationOptions(new SvgRasterizationOptions()
{{
setPageSize(new SizeF(image.getWidth(), image.getHeight()));
}});
}});
}
finally
{
image.dispose();
}
}
private void save(final boolean useEmbedded, String fileName, int expectedCountFonts)
{
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 fontFolder;
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);
fontFolder = FontFolder + "\\" + testingFileName;
image.save(outputFile,
new SvgOptions()
{{
setVectorRasterizationOptions(emfRasterizationOptions);
setCallback(
new SvgCallbackFontTest(useEmbedded, fontFolder)
{{
setLink(FontFolderName +"/"+testingFileName);
}});
}});
}
finally
{
image.dispose();
}
if (!useEmbedded)
{
f = new File(fontFolder);
String[] files = f.list();
if (files.length != expectedCountFonts)
{
throw new RuntimeException(String.format(
"Expected count font files = %d, Current count font files = %d", expectedCountFonts,
files.length));
}
}
}
}
class SvgCallbackFontTest extends SvgResourceKeeperCallback
{
/**
* The out folder
*/
private final String outFolder;
/**
* The use embedded font
*/
private final boolean useEmbeddedFont;
/**
* The font counter
*/
private int fontCounter = 0;
/**
* Initializes a new instance of the {@see SvgTests.svgCallbackFontTest} class.
* @param useEbeddedFont if set to true [use ebedded font].
* @param outFolder The out folder.
*/
public SvgCallbackFontTest(boolean useEbeddedFont, String outFolder)
{
this.useEmbeddedFont = useEbeddedFont;
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;
}
/**
* Called when font resource ready to be saved to storage.
* @param args The arguments.
*/
public void onFontResourceReady(FontStoringArgs args)
{
if (this.useEmbeddedFont)
{
args.setFontStoreType(FontStoreType.Embedded);
}
else
{
args.setFontStoreType(FontStoreType.Stream);
String fontFolder = this.outFolder;
File f = new File(fontFolder);
if (!f.exists())
{
f.mkdirs();
}
String fName = args.getSourceFontFileName();
f = new File(fName);
if (!f.exists())
{
fName = String.format("font_%d.ttf", this.fontCounter++);
f = new File(fName);
}
String name = f.getName();
name = name.substring(name.indexOf('\\')+1);
String fileName = fontFolder + "\\" + name;
args.setDestFontStream(new FileStream(fileName, FileMode.OpenOrCreate));
args.setDisposeStream(true);
args.setFontFileUri("./" + this.getLink() + "/" + name);
}
}
// 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");
// Cast object of Image to RasterImage
RasterImage rasterImage = (RasterImage) image;
// Check if RasterImage is cached
if (!rasterImage.isCached()) {
// Cache RasterImage for better performance
rasterImage.cacheData();
}
// Adjust the brightness
rasterImage.adjustBrightness(70);
// Create an instance of TiffOptions for the resultant image
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.Default);
// Set various properties for the object of TiffOptions
tiffOptions.setBitsPerSample(new int[] { 8, 8, 8 });
tiffOptions.setPhotometric(TiffPhotometrics.Rgb);
// Save the resultant image to TIFF format
rasterImage.save(dataDir + "AdjustBrightness_out.tiff", tiffOptions);
// 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");
// Cast object of Image to RasterImage
RasterImage rasterImage = (RasterImage)image;
// Check if RasterImage is cached
if (!rasterImage.isCached())
{
// Cache RasterImage for better performance
rasterImage.cacheData();
}
// Adjust the contrast
rasterImage.adjustContrast(10);
// Create an instance of TiffOptions for the resultant image
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.Default);
// Set various properties for the object of TiffOptions
tiffOptions.setBitsPerSample( new int[] { 8, 8, 8 });
tiffOptions.setPhotometric(TiffPhotometrics.Rgb);
// Save the resultant image to TIFF format
rasterImage.save(dataDir + "AdjustingContrast_out.tiff", tiffOptions);
// 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");
// Cast object of Image to RasterImage
RasterImage rasterImage = (RasterImage)image;
// Check if RasterImage is cached
if (!rasterImage.isCached())
{
// Cache RasterImage for better performance
rasterImage.cacheData();
}
// Adjust the gamma
rasterImage.adjustGamma(2.2f, 2.2f, 2.2f);
// Create an instance of TiffOptions for the resultant image
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.Default);
// Set various properties for the object of TiffOptions
tiffOptions.setBitsPerSample(new int[] { 8, 8, 8 });
tiffOptions.setPhotometric(TiffPhotometrics.Rgb);
// Save the resultant image to TIFF format
rasterImage.save(dataDir + "AdjustingGamma_out.tiff", tiffOptions);
// The path to the documents directory.
String dataDir = "ModifyingImages/";
String sourceFileName = dataDir + "Colored by Faith_small.psd";
String inputPointsFileName = dataDir + "Java_ColoredByFaith_small.dat";
AutoMaskingArgs maskingArgs = new AutoMaskingArgs();
fillInputPoints(inputPointsFileName, maskingArgs);
String outputFileName = dataDir + "Colored by Faith_small_auto.png";
RasterImage image = (RasterImage) Image.load(sourceFileName);
try
{
MaskingOptions maskingOptions = new MaskingOptions();
maskingOptions.setMethod(SegmentationMethod.GraphCut);
maskingOptions.setArgs(maskingArgs);
maskingOptions.setDecompose(false);
PngOptions options = new PngOptions();
options.setColorType(PngColorType.TruecolorWithAlpha);
options.setSource(new StreamSource());
maskingOptions.setExportOptions(options);
MaskingResult[] maskingResults = new ImageMasking(image).decompose(maskingOptions);
Image resultImage = maskingResults[1].getImage();
try
{
resultImage.save(outputFileName);
}
finally
{
resultImage.close();
}
}
finally
{
image.close();
}
private static void fillInputPoints(String filePath, AutoMaskingArgs autoMaskingArgs) throws IOException
{
InputStream inputStream = new FileInputStream(filePath);
try
{
LEIntegerReader reader = new LEIntegerReader(inputStream);
boolean hasObjectRectangles = inputStream.read() != 0;
boolean hasObjectPoints = inputStream.read() != 0;
autoMaskingArgs.setObjectsRectangles(null);
autoMaskingArgs.setObjectsPoints(null);
if (hasObjectRectangles)
{
int len = reader.read();
Rectangle[] rects = new Rectangle[len];
for (int i = 0; i < len; i++)
{
// firstly Y
int y = reader.read();
// secondly X
int x = reader.read();
// width
int width = reader.read();
// height
int height = reader.read();
rects[i] = new Rectangle(x, y, width, height);
}
autoMaskingArgs.setObjectsRectangles(rects);
}
if (hasObjectPoints)
{
int len = reader.read();
Point[][] points = new Point[len][];
for (int i = 0; i < len; i++)
{
int il = reader.read();
points[i] = new Point[il];
for (int j = 0; j < il; j++)
{
int x = reader.read();
int y = reader.read();
points[i][j] = new Point(x, y);
}
}
autoMaskingArgs.setObjectsPoints(points);
}
}
finally
{
inputStream.close();
}
}
private static class LEIntegerReader
{
private final InputStream stream;
private final byte[] buffer = new byte[4];
LEIntegerReader(InputStream stream)
{
this.stream = stream;
}
int read() throws IOException
{
int len = stream.read(buffer);
if (len != 4)
{
throw new RuntimeException("Unexpected EOF");
}
return ((buffer[3] & 0xff) << 24) | ((buffer[2] & 0xff) << 16) | ((buffer[1] & 0xff) << 8) | (buffer[0] & 0xFF);
}
}
// 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");
// Convert the image into RasterImage.
RasterImage rasterImage = (RasterImage) image;
// Pass Bounds[rectangle] of image and GaussianBlurFilterOptions
// instance to Filter method.
rasterImage.filter(rasterImage.getBounds(), new GaussianBlurFilterOptions(5, 5));
// Save the results to output path.
rasterImage.save(dataDir + "BluranImage_out.gif");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String dataDir = Utils.getSharedDataDir(ChangeWindowSize.class) + "ModifyingImages/";
String sourceFileName = "test.png";
String outputFileName = "result.png";
PngImage image = (PngImage)Image.load(dataDir+sourceFileName);
try
{
image.binarizeBradley(10, 20);
image.save(dataDir+outputFileName);
}
finally
{
image.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
public static void main(String... args) throws IOException
{
String dataDir = Utils.getSharedDataDir(CMYKPSDToCMYKTiff.class) + "ModifyingImages/";
String folder = "D:\\tiff\\";
//With IccProfile
CMYKPSDToCMYKTiff.psdToTiffCmyk(folder,true);
//Without IccProfile
CMYKPSDToCMYKTiff.psdToTiffCmyk(folder, false);
}
private static void psdToTiffCmyk(String folder, boolean isIccProfile) throws IOException
{
String fileName = String.format("cmyk_%b.tiff", isIccProfile);
String inputFile = folder + "cmyk.psd";
String inputIccFile = folder + "JapanWebCoated.icc";
String outputFile = folder + fileName;
Image image = Image.load(inputFile);
try
{
if (isIccProfile)
{
FileInputStream f = new FileInputStream(inputIccFile);
final byte[] icc = new byte[f.available()];
f.read(icc);
f.close();
image.save(outputFile, new TiffOptions(TiffExpectedFormat.TiffLzwCmyk)
{{
setIccProfile(icc);
}
public void setIccProfile(byte[] icc) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
}
else
{
image.save(outputFile, new TiffOptions(TiffExpectedFormat.TiffLzwCmyk));
}
}
finally
{
image.dispose();
}
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String fileName = "photooverlay_5_new";
PngOptions pngOptions = new PngOptions() {{ setColorType(PngColorType.TruecolorWithAlpha); }};
PsdImage input = (PsdImage)Image.load(fileName + ".psd");
try
{
for (Layer layer : input.getLayers())
{
if (layer.getName().equals("Maincolor"))
{
layer.replaceNonTransparentColors(Orange);
// replaceNonTransparentColors(Color.getOrange());
input.save(fileName + "_nonTransparentColors_result.png");
input.save(fileName + "_nonTransparentColors_result.psd");
break;
}
}
}
finally
{
input.dispose();
}
input = (PsdImage)Image.load(fileName + ".psd");
try
{
for (Layer layer : input.getLayers())
{
if (layer.getName().equals("Maincolor"))
{
layer.replaceColor(LightGreen,(byte)40,Orange);
input.save(fileName + "_specificColor_result.png");
input.save(fileName + "_specificColor_result.psd");
break;
}
}
}
finally
{
input.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String srcDir = "IMAGINGNET-2160\\";
String outputFolder = "C:\\temp\\";
int[] colorTypes = new int[]
{
JpegCompressionColorMode.Grayscale,
JpegCompressionColorMode.YCbCr,
JpegCompressionColorMode.Rgb,
JpegCompressionColorMode.Cmyk,
JpegCompressionColorMode.Ycck,
};
String[] sourceFileNames = new String[]
{
"Rgb.jpg",
"Rgb.jpg",
"Rgb.jpg",
"Rgb.jpg",
"Rgb.jpg",
};
JpegOptions options = new JpegOptions();
options.setBitsPerChannel((byte)12);
for (int i = 0; i < colorTypes.length; ++i)
{
options.setColorType(colorTypes[i]);
String fileName = JpegCompressionColorMode.getName(JpegCompressionColorMode.class, colorTypes[i]) + " 12-bit.jpg";
String referencePath = srcDir + fileName;
String outputPath = outputFolder + fileName;
Image image = Image.load(srcDir + sourceFileNames[i]);
try
{
image.save(outputPath, options);
}
finally
{
image.dispose();
}
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
JpegImage image = (JpegImage) Image.load(dataDir + "aspose-logo.jpg");
// Perform Floyd Steinberg dithering on the current image
image.dither(DitheringMethod.ThresholdDithering, 4);
// Save the resultant image
image.save(dataDir + "DitheringRasterImages_out.bmp");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String fileName = "testReplacementNotAvailableFonts.psd";
PsdImage image = (PsdImage)Image.load(fileName, new PsdLoadOptions(){{ setDefaultReplacementFont ("Arial"); }});
try
{
image.save("result.png", new PngOptions() {{ setColorType(PngColorType.TruecolorWithAlpha); }});
}
finally
{
image.dispose();
}
// The path to the documents directory.
String dataDir = "ModifyingImages/";
String sourceFileName = dataDir + "Colored by Faith_small.psd";
String outputFileName = dataDir + "Colored by Faith_small_manual.png";
GraphicsPath manualMask = new GraphicsPath();
Figure firstFigure = new Figure();
firstFigure.addShape(new EllipseShape(new RectangleF(100, 30, 40, 40)));
firstFigure.addShape(new RectangleShape(new RectangleF(10, 200, 50, 30)));
manualMask.addFigure(firstFigure);
GraphicsPath subPath = new GraphicsPath();
Figure secondFigure = new Figure();
secondFigure.addShape(
new PolygonShape(new PointF[]{
new PointF(310, 100), new PointF(350, 200), new PointF(250, 200)
}, true));
secondFigure.addShape(new PieShape(new RectangleF(10, 10, 80, 80), 30, 120));
subPath.addFigure(secondFigure);
manualMask.addPath(subPath);
RasterImage image = (RasterImage) Image.load(sourceFileName);
try
{
MaskingOptions maskingOptions = new MaskingOptions();
maskingOptions.setMethod(SegmentationMethod.Manual);
maskingOptions.setDecompose(false);
ManualMaskingArgs argus = new ManualMaskingArgs();
argus.setMask(manualMask);
maskingOptions.setArgs(argus);
PngOptions options = new PngOptions();
options.setColorType(PngColorType.TruecolorWithAlpha);
options.setSource(new StreamSource());
maskingOptions.setExportOptions(options);
MaskingResult[] maskingResults = new ImageMasking(image).decompose(maskingOptions);
Image resultImage = maskingResults[1].getImage();
try
{
resultImage.save(outputFileName);
}
finally
{
resultImage.close();
}
}
finally
{
image.close();
}
// 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");
if (!image.isCached()) {
image.cacheData();
}
// specifying width and height
int newWidth = image.getWidth() / 2;
image.resizeHeightProportionally(newWidth);
int newHeight = image.getHeight() / 2;
image.resizeHeightProportionally(newHeight);
// saving result
image.save(dataDir + "ResizeImageProportionally_out.png");
// 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");
if (!image.isCached()) {
image.cacheData();
}
// specifying only width and ResizeType
int newWidth = image.getWidth() / 2;
image.resizeWidthProportionally(newWidth, ResizeType.LanczosResample);
// specifying only height and ResizeType
int newHeight = image.getHeight() / 2;
image.resizeHeightProportionally(newHeight, ResizeType.NearestNeighbourResample);
// saving result
image.save(dataDir + "ResizeImageWithResizeTypeEnumeration_out.png");
// 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.png");
image.resize(300, 300, ResizeType.LanczosResample);
image.save(dataDir + "SimpleResizing_out.jpg");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// loading an Image
Image image = Image.load(dataDir + "aspose-logo.jpg");
// Rotating Image
image.rotateFlip(RotateFlipType.Rotate270FlipNone);
image.save(dataDir + "RotatingAnImage_out.jpg");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
RasterImage image = (RasterImage) Image.load(dataDir + "aspose-logo.jpg");
// Before rotation, the image should be cached for better performance
if (!image.isCached()) {
image.cacheData();
}
// Perform the rotation on 20 degree while keeping the image size
image.rotate(20f);
// Save the result to a new file
image.save(dataDir + "RotatingImageOnSpecificAngle_out.jpg");
// 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");
if (!image.isCached()) {
image.cacheData();
}
// specifying width and height
int newWidth = image.getWidth() / 2;
image.resizeWidthProportionally(newWidth);
int newHeight = image.getHeight() / 2;
image.resizeHeightProportionally(newHeight);
// saving result
image.save(dataDir + "SimpleResizeImageProportionally_out.png");
// 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");
image.resize(300, 300);
image.save(dataDir + "SimpleResizing_out.jpg");
String dataDir = Utils.getSharedDataDir(SupportForReplacingMissingFonts.class) + "ModifyingImages/";
FontSettings.setDefaultFontName("Comic Sans MS");
String[] files = new String[] { "missing-font.emf", "missing-font.odg", "missing-font.svg", "missing-font.wmf" };
VectorRasterizationOptions[] options = new VectorRasterizationOptions[] { new EmfRasterizationOptions(), new OdgRasterizationOptions(), new SvgRasterizationOptions(), new WmfRasterizationOptions() };
for (int i = 0; i < files.length; i++)
{
String outFile = dataDir + files[i] + ".png";
Image img = Image.load(dataDir + files[i]);
try
{
options[i].setPageWidth(img.getWidth());
options[i].setPageHeight(img.getHeight());
PngOptions saveOptions = new PngOptions();
saveOptions.setVectorRasterizationOptions(options[i]);
img.save(outFile, saveOptions);
}
finally
{
img.close();
}
}
// 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");
image.resize(300, 300);
image.save(dataDir + "SimpleResizing_out.jpg");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
Image image = Image.load("test.bmp");
try
{
image.save("test.bmp.png", new PngOptions());
}
finally
{
image.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String filePath = "ill_bado_gs723.psd";
Image image = Image.load(filePath);
try
{
// Cast image object to PSD image
PsdImage psdImage = (PsdImage)image;
// Create an instance of PngOptions class
PngOptions pngOptions = new PngOptions();
pngOptions.setColorType(PngColorType.TruecolorWithAlpha);
image.save("result.png", pngOptions);
}
finally
{
image.dispose();
}
// The path to the documents directory.
String basePath = Utils.getSharedDataDir(ManualImageMasking.class) + "ModifyingImages/";
String[] files = new String[] {
"SmoothingTest.cdr",
"SmoothingTest.cmx",
"SmoothingTest.emf",
"SmoothingTest.wmf",
"SmoothingTest.odg",
"SmoothingTest.svg"
};
int[] smoothingModes = new int[] {
SmoothingMode.AntiAlias, SmoothingMode.None
};
for (String fileName: files) {
Image image = Image.load(basePath + fileName);
try {
VectorRasterizationOptions vectorRasterizationOptions;
if (image instanceof CdrImage) {
vectorRasterizationOptions = new CdrRasterizationOptions();
} else if (image instanceof CmxImage) {
vectorRasterizationOptions = new CmxRasterizationOptions();
} else if (image instanceof EmfImage) {
vectorRasterizationOptions = new EmfRasterizationOptions();
} else if (image instanceof WmfImage) {
vectorRasterizationOptions = new WmfRasterizationOptions();
} else if (image instanceof OdgImage) {
vectorRasterizationOptions = new OdgRasterizationOptions();
} else if (image instanceof SvgImage) {
vectorRasterizationOptions = new SvgRasterizationOptions();
} else {
throw new RuntimeException("This is image is not supported in this example");
}
vectorRasterizationOptions.setPageSize(Size.to_SizeF(image.getSize()));
for (int smoothingMode: smoothingModes) {
String outputFileName = basePath + String.format("image_%s%s.png", TextRenderingHint.toString(SmoothingMode.class, smoothingMode), fileName.substring(fileName.lastIndexOf('.')));
vectorRasterizationOptions.setSmoothingMode(smoothingMode);
PngOptions pngOptions = new PngOptions();
pngOptions.setVectorRasterizationOptions(vectorRasterizationOptions);
image.save(outputFileName, pngOptions);
}
} finally {
image.close();
}
}
// The path to the documents directory.
String basePath = Utils.getSharedDataDir(ManualImageMasking.class) + "ModifyingImages/";
String[] files = new String[] {
"TextHintTest.cdr",
"TextHintTest.cmx",
"TextHintTest.emf",
"TextHintTest.wmf",
"TextHintTest.odg",
"TextHintTest.svg"
};
int[] textRenderingHints = new int[] {
TextRenderingHint.AntiAlias, TextRenderingHint.AntiAliasGridFit,
TextRenderingHint.ClearTypeGridFit, TextRenderingHint.SingleBitPerPixel, TextRenderingHint.SingleBitPerPixelGridFit
};
for (String fileName: files) {
Image image = Image.load(basePath + fileName);
try {
VectorRasterizationOptions vectorRasterizationOptions;
if (image instanceof CdrImage) {
vectorRasterizationOptions = new CdrRasterizationOptions();
} else if (image instanceof CmxImage) {
vectorRasterizationOptions = new CmxRasterizationOptions();
} else if (image instanceof EmfImage) {
vectorRasterizationOptions = new EmfRasterizationOptions();
} else if (image instanceof WmfImage) {
vectorRasterizationOptions = new WmfRasterizationOptions();
} else if (image instanceof OdgImage) {
vectorRasterizationOptions = new OdgRasterizationOptions();
} else if (image instanceof SvgImage) {
vectorRasterizationOptions = new SvgRasterizationOptions();
} else {
throw new RuntimeException("This is image is not supported in this example");
}
vectorRasterizationOptions.setPageSize(Size.to_SizeF(image.getSize()));
for (int textRenderingHint: textRenderingHints) {
String outputFileName = basePath + String.format("image_%s%s.png", TextRenderingHint.toString(TextRenderingHint.class, textRenderingHint), fileName.substring(fileName.lastIndexOf('.')));
vectorRasterizationOptions.setTextRenderingHint(textRenderingHint);
PngOptions pngOptions = new PngOptions();
pngOptions.setVectorRasterizationOptions(vectorRasterizationOptions);
image.save(outputFileName, pngOptions);
}
} finally {
image.close();
}
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String outputFile = dataDir + "AdditionalOptions_out.psd";
// Load an existing PSD file as Image
com.aspose.imaging.Image image = com.aspose.imaging.Image.load(sourceFileName);
try {
// Convert Image to PsdImage.
com.aspose.imaging.fileformats.psd.PsdImage psdImage = (com.aspose.imaging.fileformats.psd.PsdImage) image;
// Get all layers inside PSD file.
Layer[] arrLayers = psdImage.getLayers();
// Count total number of layers and iterate through each layer.
int layers = arrLayers.length;
for (int i = 0; i < layers; i++) {
// Check if layer is a text layer.
if (arrLayers[i] instanceof com.aspose.imaging.fileformats.psd.layers.TextLayer) {
// Convert the layer to TextLayer.
com.aspose.imaging.fileformats.psd.layers.TextLayer textLayer1 = (com.aspose.imaging.fileformats.psd.layers.TextLayer) arrLayers[i];
// Update the text in text layer.
textLayer1.updateText("IK Changed TEXT");
}
}
// Create an instance of PsdOptions class.
com.aspose.imaging.imageoptions.PsdOptions psdOpt = new com.aspose.imaging.imageoptions.PsdOptions();
// Call setCompressionMethod method.
psdOpt.setCompressionMethod(CompressionMethod.RLE);
// Call setRemoveGlobalTextEngineResource with value TRUE to informs
// that global text resources must be removed.
psdOpt.setRemoveGlobalTextEngineResource(true);
// Save the updated PSD file.
psdImage.save(outputFile, psdOpt);
} finally {
image.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Create an instance of Image class
String sourceFileName = dataDir + "samplePsd.psd";
com.aspose.imaging.Image image = com.aspose.imaging.Image.load(sourceFileName);
// Cast image object to PSD image
com.aspose.imaging.fileformats.psd.PsdImage psdImage = (com.aspose.imaging.fileformats.psd.PsdImage) image;
// Create an instance of PngOptions class
PngOptions pngOptions = new PngOptions();
pngOptions.setColorType(com.aspose.imaging.fileformats.png.PngColorType.TruecolorWithAlpha);
// Access the list of layers in the PSD image object
com.aspose.imaging.fileformats.psd.layers.Layer[] allLayers = psdImage.getLayers();
for (int i = 0; i < allLayers.length; i++) {
// convert and save the layer to PNG file format.
allLayers[i].save("ConvertPSDLayerstoRasterImages_out" + i + 1 + ".png", pngOptions);
}
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String sourceFileName = dataDir + "samplePsd.psd";
String outputFileName = dataDir + "result.psd";
PsdImage image = (PsdImage) Image.load(sourceFileName);
// Iterate over the PSD resources
for (ResourceBlock resource : image.getImageResources()) {
// Check if the resource is of thumbnail type
if (resource instanceof ThumbnailResource) {
// Retrieve the ThumbnailResource
ThumbnailResource thumbnail = (ThumbnailResource) resource;
// Check the format of the ThumbnailResource
if (thumbnail.getFormat() == ThumbnailFormat.KJpegRgb) {
// Create a new BmpImage by specifying the width and height
BmpImage thumnailImage = new BmpImage(thumbnail.getWidth(), thumbnail.getHeight());
// Store the pixels of thumbnail on to the newly created BmpImage
thumnailImage.savePixels(thumnailImage.getBounds(), thumbnail.getThumbnailData());
// Save thumbnail on disc
thumnailImage.save(outputFileName);
}
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
PsdOptions createOptions = new PsdOptions();
// Set source
createOptions.setSource(new FileCreateSource(dataDir + "output.psd", false));
// Set ColorMode to Indexed
createOptions.setColorMode(ColorModes.Indexed);
// Set PSD file version
createOptions.setVersion(5);
// Create a new color patelle having RGB colors
Color[] palette = new Color[] { Color.getRed(), Color.getGreen(), Color.getBlue() };
// Set Palette property to newly created palette
createOptions.setPalette(new com.aspose.imaging.fileformats.psd.PsdColorPalette(palette));
// Set compression method
createOptions.setCompressionMethod(CompressionMethod.RLE);
// Create a new PSD with PsdOptions created previously
PsdImage psd = (PsdImage) PsdImage.create(createOptions, 500, 500);
// Draw some graphics over the newly created PSD
Graphics graphics = new Graphics(psd);
graphics.clear(Color.getWhite());
graphics.drawEllipse(new Pen(Color.getRed(), 6), new Rectangle(0, 0, 400, 400));
psd.save();
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Create an instance of Image class and load PSD file as image.
com.aspose.imaging.Image objImage = com.aspose.imaging.Image.load(flattenPath);
// Cast image object to PSD image
com.aspose.imaging.fileformats.psd.PsdImage psdImage = (com.aspose.imaging.fileformats.psd.PsdImage) objImage;
// do processing
// Get the true value if PSD is flatten and false in case the PSD is not flatten.
System.out.println(psdImage.isFlatten());
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String sourceFileName = dataDir + "sample.bmp";
Image image = Image.load(sourceFileName);
// Create an instance of PsdOptions and set it�s various properties
PsdOptions psdOptions = new PsdOptions();
psdOptions.setColorMode(ColorModes.Rgb);
psdOptions.setCompressionMethod(CompressionMethod.RLE);
psdOptions.setVersion(4);
// Save image to disk in PSD format
image.save(dataDir + "ExportImagestoPSDFormat_out.psd", psdOptions);
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Create an instance of Image class and load PSD file as image.
com.aspose.imaging.Image objImage = com.aspose.imaging.Image.load(sourceFileName);
// Cast image object to PSD image
com.aspose.imaging.fileformats.psd.PsdImage psdImage = (com.aspose.imaging.fileformats.psd.PsdImage) objImage;
// Create an instance of PngOptions class
com.aspose.imaging.imageoptions.PngOptions pngOptions = new com.aspose.imaging.imageoptions.PngOptions();
pngOptions.setColorType(com.aspose.imaging.fileformats.png.PngColorType.TruecolorWithAlpha);
// Loop through the list of layers
for (int i = 0; i < psdImage.getLayers().length; i++) {
// convert and save the layer to PNG file format.
psdImage.getLayers()[i].save("ExportPSDLayertoRasterImage_out" + i + 1 + ".png", pngOptions);
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
public static void main(String... args) throws Exception {
String dataDir = Utils.getSharedDataDir(ExtractICCProfileIgnoreICC.class) + "Photoshop/";
String sourcePath = dataDir + "gray-d15.psd";
String outputPath = dataDir + "gray-d15.psd.ignore-icc.tif";
// Save to grayscale TIFF
TiffOptions saveOptions = new TiffOptions(TiffExpectedFormat.Default);
saveOptions.setPhotometric(TiffPhotometrics.MinIsBlack);
saveOptions.setBitsPerSample(new int[] { 8 });
// If the image contains a built-in Gray ICC profile, it is not be applied by default in contrast of the CMYK profile.
// Enable ICC conversion explicitly.
LoadOptions loadOptions = new LoadOptions();
loadOptions.setUseIccProfileConversion(false);
PsdImage psdImage = (PsdImage)Image.load(sourcePath, loadOptions);
try
{
// Embed the gray ICC profile to the output TIFF.
// The built-in Gray Profile can be read via the PsdImage.GrayColorProfile property.
saveOptions.setIccProfile(toMemoryStream(psdImage.getGrayColorProfile()));
psdImage.save(outputPath, saveOptions);
}
finally
{
psdImage.dispose();
}
}
private static byte[] toMemoryStream(StreamSource streamSource)
{
StreamContainer sc = streamSource.getStreamContainer();
try
{
return sc.toBytes();
}
finally
{
sc.dispose();
}
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
public static void main(String... args) throws Exception {
String dataDir = Utils.getSharedDataDir(ICCProfileExtraction.class) + "Photoshop/";
PsdImage psdImage = (PsdImage)Image.load(dataDir + "gray-d15.psd");
try{
StreamSource grayProfile = psdImage.getGrayColorProfile();
// Save to grayscale TIFF
TiffOptions saveOptions = new TiffOptions(TiffExpectedFormat.Default);
saveOptions.setPhotometric(TiffPhotometrics.MinIsBlack);
saveOptions.setBitsPerSample(new int[] { 8 });
// No ICC profile
psdImage.save(dataDir + "gray-d15.psd.noprofile.tif", saveOptions);
// Embed ICC profile
saveOptions.setIccProfile(toMemoryStream(grayProfile));
psdImage.save(dataDir + "gray-d15.psd.tif", saveOptions);
}
finally{
psdImage.dispose();
}
}
private static byte[] toMemoryStream(StreamSource streamSource)
{
StreamContainer sc = streamSource.getStreamContainer();
try
{
return sc.toBytes();
}
finally
{
sc.dispose();
}
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String sourceFileName = dataDir + "samplePsd.psd";
String outputFileName = dataDir + "ImportanImageToPSDLayer_out.psd";
// Load a PSD file as an image and caste it into PsdImage
com.aspose.imaging.fileformats.psd.PsdImage image = (com.aspose.imaging.fileformats.psd.PsdImage) com.aspose.imaging.Image
.load(sourceFileName);
//Extract a layer from PSDImage
com.aspose.imaging.fileformats.psd.layers.Layer layer = image.getLayers()[1];
// Load the image that is needed to be imported into the PSD file.
String normalImagePath = dataDir + "aspose_logo.png";
com.aspose.imaging.RasterImage drawImage = (com.aspose.imaging.RasterImage) com.aspose.imaging.Image
.load(normalImagePath);
// Call DrawImage method of the Layer class and pass the image instance.
layer.drawImage(new com.aspose.imaging.Point(10, 10), drawImage);
// Save the results to output path.
image.save(outputFileName, new com.aspose.imaging.imageoptions.PsdOptions());
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String sourceFile = dataDir + "layerLock.psd";
String outputFile = dataDir + "result.psd";
PsdImage image = (PsdImage)Image.load(sourceFile);
try
{
Layer[] layers = image.getLayers();
layers[4].setLayerLock(com.aspose.imaging.fileformats.psd.layers.layerresources.LayerLockType.LockAll);
layers[2].setLayerLock(com.aspose.imaging.fileformats.psd.layers.layerresources.LayerLockType.None);
layers[3].setLayerLock(com.aspose.imaging.fileformats.psd.layers.layerresources.LayerLockType.LockTransparentPixels);
layers[1].setLayerLock(com.aspose.imaging.fileformats.psd.layers.layerresources.LayerLockType.LockImagePixels);
layers[5].setLayerLock(com.aspose.imaging.fileformats.psd.layers.layerresources.LayerLockType.LockPosition);
layers[5].setFlags(com.aspose.imaging.fileformats.psd.layers.LayerFlags.TransparencyProtected);
image.save(outputFile);
}
finally
{
image.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String sourceFileName = dataDir + "samplePsd.psd";
// Load an existing PSD file as image
com.aspose.imaging.Image image = com.aspose.imaging.Image.load(sourceFileName);
// Convert the loaded image to PSDImage
com.aspose.imaging.fileformats.psd.PsdImage psdImage = (com.aspose.imaging.fileformats.psd.PsdImage) image;
// create a JPG file stream
java.io.FileInputStream fs = new java.io.FileInputStream(dataDir + "aspose-logo.jpg");
// Create JPEG option class object
JpegOptions jpgOptions = new JpegOptions();
// call the Save the method of PSDImage class to merge the layers and
// save it as jpg image.
psdImage.save(dataDir + "MergPSDlayers_out.jpg", jpgOptions);
String dataDir = Utils.getSharedDataDir(RenderingOfRotatedTextLayerByTransformMatrix.class) + "Photoshop/";
String sourceFileName = dataDir + "TransformedText.psd";
String exportPath = dataDir + "TransformedTextExport.psd";
String exportPathPng = dataDir + "TransformedTextExport.png";
PsdImage im = (PsdImage) Image.load(sourceFileName);
try
{
im.save(exportPath);
im.save(exportPathPng, new PngOptions()
{{
setColorType(PngColorType.TruecolorWithAlpha);
}});
}
finally
{
im.close();
}
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(SetFontsFolder.class) + "Photoshop/";
String sourceFile = dataDir+"grinched-regular-font.psd";
String output = dataDir+"grinched-regular-font.psd.png";
//Folder that contains fonts that we want to use for rendering
//(file GrinchedRegular.otf must be in this folder for proper work of example)
// You can use FontSettings.addFontsFolder or you can use FontSettings.setFontsFolder to avoid system fonts
FontSettings.addFontsFolder(dataDir+"Fonts\\");
FontSettings.updateFonts();
PsdImage image = (PsdImage) Image.load(sourceFile, new PsdLoadOptions());
try {
image.save(output, new PngOptions());
} finally {
image.close();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String dataDir = Utils.getSharedDataDir(SupportEffectsforPSD.class) + "Photoshop/";
String output = "dropShadow.png";
PsdLoadOptions psdLoadOptions=new PsdLoadOptions();
psdLoadOptions.setLoadEffectsResource(true);
psdLoadOptions.setUseDiskForLoadEffectsResource(true);
PsdImage image = (PsdImage)Image.load(dataDir+"test.psd",psdLoadOptions);
try
{
//Debug.assert_(image.getLayers()[2] != null, "Layer with effects resource was not recognized");
PngOptions pngOptions=new PngOptions();
pngOptions.setColorType (PngColorType.TruecolorWithAlpha);
image.save(output,pngOptions);
}
finally
{
image.dispose();
}
}
String dataDir = Utils.getSharedDataDir(SupportOfColorFillLayer.class) + "Photoshop/";
String sourceFileName = dataDir + "ColorFillLayer.psd";
String exportPath = dataDir + "ColorFillLayer_output.psd";
String exportPathPng = dataDir + "ColorFillLayer_output.png";
PsdImage im = (PsdImage) Image.load(sourceFileName);
try
{
for (Layer layer : im.getLayers())
{
if (layer instanceof FillLayer)
{
FillLayer fillLayer = (FillLayer) layer;
if (fillLayer.getFillSettings().getFillType() != FillType.Color)
{
throw new RuntimeException("Wrong Fill Layer");
}
IColorFillSettings settings = (IColorFillSettings) fillLayer.getFillSettings();
settings.setColor(Color.getRed());
fillLayer.update();
im.save(exportPath);
break;
}
}
}
finally
{
im.close();
}
String dataDir = Utils.getSharedDataDir(SupportOfGdFlResource.class) + "Photoshop/";
String sourceFileName = dataDir + "ComplexGradientFillLayer.psd";
String exportPath = dataDir + "ComplexGradientFillLayer_after.psd";
PsdImage im = (PsdImage) Image.load(sourceFileName);
try
{
for (Layer layer : im.getLayers())
{
if (layer instanceof FillLayer)
{
FillLayer fillLayer = (FillLayer) layer;
for (LayerResource res : fillLayer.getResources())
{
if (res instanceof GdFlResource)
{
// Reading
GdFlResource resource = (GdFlResource) res;
if (resource.getAlignWithLayer() != false ||
(Math.abs(resource.getAngle() - 45.0) > 0.001) ||
resource.getDither() != true ||
resource.getReverse() != false ||
!resource.getColor().equals(Color.getEmpty()) ||
Math.abs(resource.getHorizontalOffset() - (-39)) > 0.001 ||
Math.abs(resource.getVerticalOffset() - (-5)) > 0.001 ||
resource.getTransparencyPoints().length != 3 ||
resource.getColorPoints().length != 2)
{
throw new RuntimeException("Resource Parameters were read wrong");
}
IGradientTransparencyPoint[] transparencyPoints = resource.getTransparencyPoints();
if (Math.abs(100.0 - transparencyPoints[0].getOpacity()) > 0.25 ||
transparencyPoints[0].getLocation() != 0 ||
transparencyPoints[0].getMedianPointLocation() != 50 ||
Math.abs(50.0 - transparencyPoints[1].getOpacity()) > 0.25 ||
transparencyPoints[1].getLocation() != 2048 ||
transparencyPoints[1].getMedianPointLocation() != 50 ||
Math.abs(100.0 - transparencyPoints[2].getOpacity()) > 0.25 ||
transparencyPoints[2].getLocation() != 4096 ||
transparencyPoints[2].getMedianPointLocation() != 50)
{
throw new RuntimeException("Gradient Transparency Points were read Wrong");
}
IGradientColorPoint[] colorPoints = resource.getColorPoints();
if (!colorPoints[0].getColor().equals(Color.fromArgb(203, 64, 140)) ||
colorPoints[0].getLocation() != 0 ||
colorPoints[0].getMedianPointLocation() != 50 ||
!colorPoints[1].getColor().equals(Color.fromArgb(203, 0, 0)) ||
colorPoints[1].getLocation() != 4096 ||
colorPoints[1].getMedianPointLocation() != 50)
{
throw new RuntimeException("Gradient Color Points were read Wrong");
}
// Editing
resource.setAngle(30.0);
resource.setDither(false);
resource.setAlignWithLayer(true);
resource.setReverse(true);
resource.setHorizontalOffset(25);
resource.setVerticalOffset(-15);
List<IGradientColorPoint> newColorPoints = new ArrayList<IGradientColorPoint>();
Collections.addAll(newColorPoints, resource.getColorPoints());
List<IGradientTransparencyPoint> newTransparencyPoints = new ArrayList<IGradientTransparencyPoint>();
Collections.addAll(newTransparencyPoints, resource.getTransparencyPoints());
GradientColorPoint gr = new GradientColorPoint();
gr.setMedianPointLocation(75);
gr.setLocation(4096);
gr.setColor(Color.getViolet());
newColorPoints.add(gr);
colorPoints[1].setLocation(3000);
GradientTransparencyPoint gr2 = new GradientTransparencyPoint();
gr2.setOpacity(80.0);
gr2.setLocation(4096);
gr2.setMedianPointLocation(25);
newTransparencyPoints.add(gr2);
transparencyPoints[2].setLocation(3000);
resource.setColorPoints(newColorPoints.toArray(new IGradientColorPoint[0]));
resource.setTransparencyPoints(newTransparencyPoints.toArray(new IGradientTransparencyPoint[0]));
im.save(exportPath);
}
break;
}
break;
}
}
}
finally
{
im.close();
}
}
String dataDir = Utils.getSharedDataDir(SupportOfGradientFillLayer.class) + "Photoshop/";
String sourceFileName = dataDir + "ComplexGradientFillLayer.psd";
String outputFile = dataDir + "ComplexGradientFillLayer_output.psd";
PsdImage im = (PsdImage) Image.load(sourceFileName);
try
{
for (Layer layer : im.getLayers())
{
if (layer instanceof FillLayer)
{
FillLayer fillLayer = (FillLayer) layer;
if (fillLayer.getFillSettings().getFillType() != FillType.Gradient)
{
throw new RuntimeException("Wrong Fill Layer");
}
IGradientFillSettings settings = (IGradientFillSettings) fillLayer.getFillSettings();
if (
Math.abs(settings.getAngle() - 45) > 0.25 ||
settings.getDither() != true ||
settings.getAlignWithLayer() != false ||
settings.getReverse() != false ||
Math.abs(settings.getHorizontalOffset() - (-39)) > 0.25 ||
Math.abs(settings.getVerticalOffset() - (-5)) > 0.25 ||
settings.getTransparencyPoints().length != 3 ||
settings.getColorPoints().length != 2 ||
Math.abs(100.0 - settings.getTransparencyPoints()[0].getOpacity()) > 0.25 ||
settings.getTransparencyPoints()[0].getLocation() != 0 ||
settings.getTransparencyPoints()[0].getMedianPointLocation() != 50 ||
!settings.getColorPoints()[0].getColor().equals(Color.fromArgb(203, 64, 140)) ||
settings.getColorPoints()[0].getLocation() != 0 ||
settings.getColorPoints()[0].getMedianPointLocation() != 50)
{
throw new RuntimeException("Gradient Fill was not read correctly");
}
settings.setAngle(0.0);
settings.setDither(false);
settings.setAlignWithLayer(true);
settings.setReverse(true);
settings.setHorizontalOffset(25);
settings.setVerticalOffset(-15);
List<IGradientColorPoint> colorPoints = new ArrayList<IGradientColorPoint>();
Collections.addAll(colorPoints, settings.getColorPoints());
List<IGradientTransparencyPoint> transparencyPoints = new ArrayList<IGradientTransparencyPoint>();
Collections.addAll(transparencyPoints, settings.getTransparencyPoints());
GradientColorPoint gr1 = new GradientColorPoint();
gr1.setColor(Color.getViolet());
gr1.setLocation(4096);
gr1.setMedianPointLocation(75);
colorPoints.add(gr1);
colorPoints.get(1).setLocation(3000);
GradientTransparencyPoint gr2 = new GradientTransparencyPoint();
gr2.setOpacity(80.0);
gr2.setLocation(4096);
gr2.setMedianPointLocation(25);
transparencyPoints.add(gr2);
transparencyPoints.get(2).setLocation(3000);
settings.setColorPoints(colorPoints.toArray(new IGradientColorPoint[0]));
settings.setTransparencyPoints(transparencyPoints.toArray(new IGradientTransparencyPoint[0]));
fillLayer.update();
im.save(outputFile, new PsdOptions(im));
break;
}
}
}
finally
{
im.close();
}
String dataDir = Utils.getSharedDataDir(SupportOfSoCoResource.class) + "Photoshop/";
// Support of SoCoResource
String sourceFileName = dataDir +"ColorFillLayer.psd";
String exportPath = dataDir +"SoCoResource_Edited.psd";
PsdImage im = (PsdImage) Image.load(sourceFileName);
try
{
for (Layer layer : im.getLayers())
{
if (layer instanceof FillLayer)
{
FillLayer fillLayer = (FillLayer) layer;
for (LayerResource resource : fillLayer.getResources())
{
if (resource instanceof SoCoResource)
{
SoCoResource socoResource = (SoCoResource) resource;
Assert.areEqual(Color.fromArgb(63, 83, 141), socoResource.getColor());
socoResource.setColor(Color.getRed());
break;
}
}
break;
}
im.save(exportPath);
}
}
finally
{
im.close();
}
String dataDir = Utils.getSharedDataDir(SupportOfVmskResource.class) + "Photoshop/";
String sourceFileName = dataDir+ "Rectangle.psd";
String exportPath = dataDir + "Rectangle_changed.psd";
PsdImage im = (PsdImage)Image.load(sourceFileName);
try
{
VmskResource resource = getVmskResource(im);
// Reading
if (resource.isDisabled() != false ||
resource.isInverted() != false ||
resource.isNotLinked() != false ||
resource.getPaths().length != 7 ||
resource.getPaths()[0].getType() != VectorPathType.PathFillRuleRecord ||
resource.getPaths()[1].getType() != VectorPathType.InitialFillRuleRecord ||
resource.getPaths()[2].getType() != VectorPathType.ClosedSubpathLengthRecord ||
resource.getPaths()[3].getType() != VectorPathType.ClosedSubpathBezierKnotUnlinked ||
resource.getPaths()[4].getType() != VectorPathType.ClosedSubpathBezierKnotUnlinked ||
resource.getPaths()[5].getType() != VectorPathType.ClosedSubpathBezierKnotUnlinked ||
resource.getPaths()[6].getType() != VectorPathType.ClosedSubpathBezierKnotUnlinked)
{
throw new RuntimeException("VmskResource was read wrong");
}
PathFillRuleRecord pathFillRule = (PathFillRuleRecord) resource.getPaths()[0];
InitialFillRuleRecord initialFillRule = (InitialFillRuleRecord) resource.getPaths()[1];
LengthRecord subpathLength = (LengthRecord) resource.getPaths()[2];
// Path fill rule doesn't contain any additional information
if (pathFillRule.getType() != VectorPathType.PathFillRuleRecord ||
initialFillRule.getType() != VectorPathType.InitialFillRuleRecord ||
initialFillRule.isFillStartsWithAllPixels() != false ||
subpathLength.getType() != VectorPathType.ClosedSubpathLengthRecord ||
subpathLength.isClosed() != true ||
subpathLength.isOpen() != false)
{
throw new RuntimeException("VmskResource paths were read wrong");
}
// Editing
resource.setDisabled(true);
resource.setInverted(true);
resource.setNotLinked(true);
BezierKnotRecord bezierKnot = (BezierKnotRecord) resource.getPaths()[3];
bezierKnot.getPoints()[0] = new Point(0, 0);
bezierKnot = (BezierKnotRecord) resource.getPaths()[4];
bezierKnot.getPoints()[0] = new Point(8039797, 10905190);
initialFillRule.setFillStartsWithAllPixels(true);
subpathLength.setClosed(false);
im.save(exportPath);
}
finally
{
im.close();
}
static VmskResource getVmskResource(PsdImage image)
{
Layer layer = image.getLayers()[1];
VmskResource resource = null;
LayerResource[] resources = layer.getResources();
for (int i = 0; i < resources.length; i++)
{
if (resources[i] instanceof VmskResource)
{
resource = (VmskResource) resources[i];
break;
}
}
if (resource == null)
{
throw new RuntimeException("VmskResource not found");
}
return resource;
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load an existing PSD file as Image
com.aspose.imaging.Image image = com.aspose.imaging.Image.load(sourceFileName);
try {
// Convert Image to PsdImage.
com.aspose.imaging.fileformats.psd.PsdImage psdImage = (com.aspose.imaging.fileformats.psd.PsdImage) image;
// Get all layers inside PSD file.
Layer[] arrLayers = psdImage.getLayers();
// Count total number of layers and iterate through each layer.
int layers = arrLayers.length;
for (int i = 0; i < layers; i++) {
// Check if layer is a text layer.
if (arrLayers[i] instanceof com.aspose.imaging.fileformats.psd.layers.TextLayer) {
// Convert the layer to TextLayer.
com.aspose.imaging.fileformats.psd.layers.TextLayer textLayer1 = (com.aspose.imaging.fileformats.psd.layers.TextLayer) arrLayers[i];
// Update the text in text layer.
textLayer1.updateText("IK Changed TEXT");
// Update the text with new font size and new text color in
// text layer.
textLayer1.updateText("New a", 48.0f, Color.getBlack());
}
}
// Create an instance of PsdOptions class.
com.aspose.imaging.imageoptions.PsdOptions psdOpt = new com.aspose.imaging.imageoptions.PsdOptions();
// Call setCompressionMethod method.
psdOpt.setCompressionMethod(CompressionMethod.RLE);
// Save the updated PSD file.
psdImage.save(outputFile, psdOpt);
} finally {
image.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
com.aspose.imaging.Image image = com.aspose.imaging.Image.load(sourceFileName);
try {
com.aspose.imaging.fileformats.psd.PsdImage psdImage = (com.aspose.imaging.fileformats.psd.PsdImage) image;
com.aspose.imaging.fileformats.psd.layers.TextLayer textLayer1 = (com.aspose.imaging.fileformats.psd.layers.TextLayer) psdImage
.getLayers()[1];
com.aspose.imaging.fileformats.psd.layers.TextLayer textLayer2 = (com.aspose.imaging.fileformats.psd.layers.TextLayer) psdImage
.getLayers()[2];
textLayer2.updateText("test update", new com.aspose.imaging.Point(100, 100), 72.0f,
com.aspose.imaging.Color.getPurple());
com.aspose.imaging.imageoptions.PsdOptions psdOpt = new com.aspose.imaging.imageoptions.PsdOptions();
psdOpt.setCompressionMethod(com.aspose.imaging.fileformats.psd.CompressionMethod.RLE);
psdImage.save(outputFile);
} finally {
image.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Creates an instance of BmpOptions and set its various properties
com.aspose.imaging.imageoptions.BmpOptions bmpCreateOptions = new com.aspose.imaging.imageoptions.BmpOptions();
bmpCreateOptions.setBitsPerPixel(32);
// Define the source property for the instance of BmpCreateOptions
bmpCreateOptions.setSource(new com.aspose.imaging.sources.StreamSource(new java.io.ByteArrayInputStream(new byte[100 * 100 * 4])));
// Creates an instance of Image and call Create method by passing the BmpOptions object
com.aspose.imaging.Image image = com.aspose.imaging.Image.create(bmpCreateOptions, 100, 100);
// Create and initialize an instance of Graphics class
com.aspose.imaging.Graphics graphic = new com.aspose.imaging.Graphics(image);
// Clear the image surface with Yellow color
graphic.clear(com.aspose.imaging.Color.getYellow());
// Draw a dotted arc shape by specifying the Pen object having red black
// color and coordinates, height, width, start & end angles
int width = 100;
int height = 200;
int startAngle = 45;
int sweepAngle = 270;
// Draw arc to screen.
graphic.drawArc(new Pen(com.aspose.imaging.Color.getYellow()), 0, 0,width, height, startAngle, sweepAngle);
// Save all changes.
image.save(dataDir + "DrawingArc_out.bmp");
// Display Status.
System.out.println("Arc has been drawn in image successfully!");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Creates an instance of BmpOptions and set its various properties
com.aspose.imaging.imageoptions.BmpOptions bmpCreateOptions = new com.aspose.imaging.imageoptions.BmpOptions();
bmpCreateOptions.setBitsPerPixel(32);
// Define the source property for the instance of BmpOptions
bmpCreateOptions.setSource(new com.aspose.imaging.sources.StreamSource(new java.io.ByteArrayInputStream(new byte[100 * 100 * 4])));
// Creates an instance of Image and call create method by passing the bmpCreateOptions object
com.aspose.imaging.Image image = com.aspose.imaging.Image.create(bmpCreateOptions, 100, 100);
// Create and initialize an instance of Graphics class
com.aspose.imaging.Graphics graphic = new com.aspose.imaging.Graphics(image);
// Clear the image surface with Yellow color
graphic.clear(com.aspose.imaging.Color.getYellow());
// Draw a dotted ellipse shape by specifying the Pen object having red color and a surrounding Rectangle
graphic.drawEllipse(new Pen(com.aspose.imaging.Color.getRed()),new com.aspose.imaging.Rectangle(30, 10, 40, 80));
// Draw a continuous ellipse shape by specifying the Pen object having solid brush with blue color and a surrounding Rectangle
graphic.drawEllipse(new Pen(new com.aspose.imaging.brushes.SolidBrush(com.aspose.imaging.Color.getBlue())),new com.aspose.imaging.Rectangle(10, 30, 80, 40));
// Save all changes.
image.save(dataDir + "DrawingEllipse_out.bmp");
// Display Status.
System.out.println("Ellipse has been drawn in image successfully!");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//Creates an instance of BmpOptions and set its various properties
com.aspose.imaging.imageoptions.BmpOptions bmpCreateOptions = new com.aspose.imaging.imageoptions.BmpOptions();
bmpCreateOptions.setBitsPerPixel(32);
//Define the source property for the instance of BmpOptions
bmpCreateOptions.setSource(new com.aspose.imaging.sources.StreamSource(new java.io.ByteArrayInputStream(new byte[100 * 100 * 4])));
//Creates an instance of Image and call create method by passing the bmpCreateOptions object
com.aspose.imaging.Image image = com.aspose.imaging.Image.create(bmpCreateOptions,100,100);
//Create and initialize an instance of Graphics class
com.aspose.imaging.Graphics graphic = new com.aspose.imaging.Graphics(image);
//Clear the image surface with Yellow color
graphic.clear(com.aspose.imaging.Color.getYellow());
//Draw a dotted line by specifying the Pen object having blue color and co-ordinate Points
graphic.drawLine(new Pen(com.aspose.imaging.Color.getBlue()), 9, 9, 90, 90);
graphic.drawLine(new Pen(com.aspose.imaging.Color.getBlue()), 9, 90, 90, 9);
//Draw a continuous line by specifying the Pen object having Solid Brush with red color and two point structures
graphic.drawLine(new Pen(new com.aspose.imaging.brushes.SolidBrush(com.aspose.imaging.Color.getRed())), new com.aspose.imaging.Point(9, 9), new com.aspose.imaging.Point(9, 90));
//Draw a continuous line by specifying the Pen object having Solid Brush with aqua color and two point structures
graphic.drawLine(new Pen(new com.aspose.imaging.brushes.SolidBrush(com.aspose.imaging.Color.getAqua())), new com.aspose.imaging.Point(9, 90), new com.aspose.imaging.Point(90, 90));
//Draw a continuous line by specifying the Pen object having Solid Brush with black color and two point structures
graphic.drawLine(new Pen(new com.aspose.imaging.brushes.SolidBrush(com.aspose.imaging.Color.getBlack())),
new com.aspose.imaging.Point(90,90),new com.aspose.imaging.Point(90,9));
//Draw a continuous line by specifying the Pen object having Solid Brush with white color and two point structures
graphic.drawLine(new Pen(new com.aspose.imaging.brushes.SolidBrush(com.aspose.imaging.Color.getWhite()))
,new com.aspose.imaging.Point(90,9), new com.aspose.imaging.Point(9,9));
//Save all changes.
//image.save(dataDir + "outputlines.bmp");
graphic.getImage().save(dataDir + "DrawingLines_out.bmp");
// Display Status.
System.out.println("Lines have been drawn in image successfully!");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Creates an instance of BmpOptions and set its various properties
com.aspose.imaging.imageoptions.BmpOptions bmpCreateOptions = new com.aspose.imaging.imageoptions.BmpOptions();
bmpCreateOptions.setBitsPerPixel(32);
// Define the source property for the instance of BmpOptions
bmpCreateOptions.setSource(new com.aspose.imaging.sources.StreamSource(new java.io.ByteArrayInputStream(new byte[100 * 100 * 4])));
// Creates an instance of Image and call Create method by passing the bmpCreateOptionsobject
com.aspose.imaging.Image image = com.aspose.imaging.Image.create(bmpCreateOptions, 100, 100);
// Create and initialize an instance of Graphics class
com.aspose.imaging.Graphics graphic = new com.aspose.imaging.Graphics(image);
// Clear the image surface with Yellow color
graphic.clear(com.aspose.imaging.Color.getYellow());
// Draw a dotted rectangle shape by specifying the Pen object having red color and a rectangle structure
graphic.drawRectangle(new Pen(com.aspose.imaging.Color.getRed()),new com.aspose.imaging.Rectangle(30, 10, 40, 80));
// Draw a continuous rectangle shape by specifying the Pen object having solid brush with blue color and a rectangle structure
graphic.drawRectangle(new Pen(new com.aspose.imaging.brushes.SolidBrush(com.aspose.imaging.Color.getBlue())),new com.aspose.imaging.Rectangle(10, 30, 80, 40));
// Save all changes.
image.save(dataDir + "DrawingRectangle_out.bmp");
//Print message
System.out.println("Rectangle created successfully. Check output file.");
String dataDir = "Svg/";
try (Image image = Image.load(dataDir + "test.svg"))
{
BmpOptions options = new BmpOptions();
SvgRasterizationOptions svgOptions = new SvgRasterizationOptions();
svgOptions.setPageWidth(100);
svgOptions.setPageHeight(200);
options.setVectorRasterizationOptions(svgOptions);
image.save(dataDir + "test.svg_out.bmp", options);
}
String dataDir = Utils.getSharedDataDir(OpenWebPFile.class) + "WebP/";
String inputFile = dataDir + "Animation1.webp";
String outputFile = dataDir + "Animation2.webp";
ByteArrayOutputStream ms = new ByteArrayOutputStream();
try
{
WebPImage image = (WebPImage)Image.load(inputFile);
try
{
image.resize(300, 450, ResizeType.HighQualityResample);
image.crop(new Rectangle(10, 10, 200, 300));
image.rotateFlipAll(RotateFlipType.Rotate90FlipX);
image.save(ms);
}
finally
{
image.close();
}
FileOutputStream fs = new FileOutputStream(outputFile);
try
{
fs.write(ms.toByteArray());
}
finally
{
fs.close();
}
}
finally
{
ms.close();
}
String inputFileName = dataDir + "sample.wmf";
String outFileName = dataDir + "ConvertingWMFtoPDF_out.pdf";
// Load an existing WMF image
com.aspose.imaging.Image image = com.aspose.imaging.Image.load(inputFileName);
try
{
final WmfRasterizationOptions wmfRasterizationOptions = new WmfRasterizationOptions();
wmfRasterizationOptions.setBackgroundColor(Color.getWhiteSmoke());
wmfRasterizationOptions.setPageWidth(image.getWidth());
wmfRasterizationOptions.setPageHeight(image.getHeight());
// Create an instance of PdfOptions class and provide rasterization
// option
PdfOptions pdfOptions = new PdfOptions();
pdfOptions.setVectorRasterizationOptions(wmfRasterizationOptions);
// Call the save method, provide output path and PdfOptions to convert
// the WMF file to PDF and save the output
image.save(outFileName, pdfOptions);
}
finally
{
image.close();
}
// The path to the documents directory.
String dataDir = "D:/wmf/";
String inputFileName = dataDir + "thistlegirl_wmfsample.wmf";
String outputFileNamePng = dataDir + "thistlegirl_wmfsample.png";
Image image = Image.load(inputFileName);
try
{
WmfRasterizationOptions rasterizationOptions = new WmfRasterizationOptions();
rasterizationOptions.setBackgroundColor(Color.getWhiteSmoke());
rasterizationOptions.setPageWidth(image.getWidth());
rasterizationOptions.setPageHeight(image.getHeight());
PngOptions pngOptions = new PngOptions();
pngOptions.setVectorRasterizationOptions(rasterizationOptions);
image.save(outputFileNamePng, pngOptions);
}
finally
{
image.close();
}
// The path to the documents directory.
String dataDir = "D:/svg/";
String inputFileName = dataDir + "thistlegirl_wmfsample.wmf";
String outputFileNameSvg = dataDir + "thistlegirl_wmfsample.svg";
Image image = Image.load(inputFileName);
try
{
WmfRasterizationOptions rasterizationOptions = new WmfRasterizationOptions();
rasterizationOptions.setBackgroundColor(Color.getWhiteSmoke());
rasterizationOptions.setPageWidth(image.getWidth());
rasterizationOptions.setPageHeight(image.getHeight());
SvgOptions svgOptions = new SvgOptions();
svgOptions.setVectorRasterizationOptions(rasterizationOptions);
image.save(outputFileNameSvg, svgOptions);
}
finally
{
image.close();
}
String inputFileName = dataDir + "sample.wmf";
String outFileName = dataDir + "ConvertingWMFtoWebp_out.webp";
// Load an existing WMF image
com.aspose.imaging.Image image = com.aspose.imaging.Image.load(inputFileName);
try
{
// Calculate new height
double k = (image.getWidth() * 1.00) / image.getHeight();
// Create an instance of EmfRasterizationOptions class and define
// settings
WmfRasterizationOptions wmf = new WmfRasterizationOptions();
wmf.setPageWidth(400);
wmf.setPageHeight((int) Math.round(400 / k));
wmf.setBorderX(5);
wmf.setBorderY(10);
wmf.setBackgroundColor(Color.getWhiteSmoke());
// Create an instance of WebPOptions class and provide rasterization
// option
ImageOptionsBase options = new WebPOptions();
options.setVectorRasterizationOptions(wmf);
// Call the save method, provide output path and WebPOptions to
// convert the WMF file to Webp and save the output
image.save(outFileName, options);
}
finally
{
image.dispose();
}
String dataDir = "dataDir/";
// Load an existing WMF image
Image image = Image.load(dataDir + "File.wmf");
try
{
image.crop(new Rectangle(300, 200, 200, 200));
// Create an instance of EmfRasterizationOptions class and set
// different properties
EmfRasterizationOptions emf = new EmfRasterizationOptions();
emf.setPageWidth(1000);
emf.setPageHeight(1000);
emf.setBackgroundColor(Color.getWhiteSmoke());
// Create an instance of PngOptions class and provide rasterization
// option
ImageOptionsBase options = new PngOptions();
options.setVectorRasterizationOptions(emf);
// Call the save method, provide output path and PngOptions to
// convert the cropped WMF file to PNG and save the output
image.save(dataDir + "ConvertWMFToPNG_out.png", options);
}
finally
{
image.dispose();
}
String dataDir = Utils.getSharedDataDir(CropWMFFile.class) + "WMF/";
WmfImage image = (WmfImage)Image.load(dataDir + "test.wmf");
image.crop(new Rectangle(10, 10, 100, 150));
System.out.println(image.getWidth());
System.out.println(image.getHeight());
image.save(dataDir + "test.wmf_crop.wmf");
// Load an existing WMF image
Image image = Image.load(dataDir + "input.wmf");
try
{
// Call the resize method of Image class and width,height values
image.resize(100, 100);
// calculate new PNG image height
double k = (image.getWidth() * 1.00) / image.getHeight();
// Create an instance of EmfRasterizationOptions class and set
// different properties
EmfRasterizationOptions emf = new EmfRasterizationOptions();
emf.setPageWidth(100);
emf.setPageHeight((int) Math.round(100 / k));
emf.setBorderX(5);
emf.setBorderY(10);
emf.setBackgroundColor(Color.getWhiteSmoke());
// Create an instance of PngOptions class and provide rasterization
// option
ImageOptionsBase options = new PngOptions();
options.setVectorRasterizationOptions(emf);
// Call the save method, provide output path and PngOptions to
// convert the WMF file to PNG and save the output
image.save(dataDir + "CreateEMFMetaFileImage_out.png", options);
}
finally
{
image.close();
}
String file = "example.svg";
String baseFolder = "D:\\Compressed\\";
String inputFile = baseFolder + file;
String outFile = inputFile + ".svgz";
try (final Image image = Image.load(inputFile))
{
image.save(outFile, new SvgOptions()
{{
setCompress(true);
}});
}
String inputFileName = "Logotype.svg";
try (Image image = Image.load(inputFileName))
{
image.resize(image.getWidth() * 10,image.getHeight() * 15);
image.save("Logotype_10_15.png", new PngOptions());
}
String file = "example.svgz";
String baseFolder = "D:\\Compressed\\";
String inputFile = baseFolder + file;
String outFile = inputFile + ".svg";
try (final Image image = Image.load(inputFile))
{
image.save(outFile, new SvgOptions()
{{
setCompress(false);
}});
}
try (TiffImage tiffImage = (TiffImage)Image.load("10MB_Tif.tif"))
{
tiffImage.rotate(90);
tiffImage.save("rotated.tif");
}
try (Image image = Image.load("Sample.tif"))
{
image.save("SampleWithPaths.psd", new PsdOptions());
}
import com.aspose.imaging.Image;
import com.aspose.imaging.imageoptions.GifOptions;
try (com.aspose.imaging.fileformats.webp.WebPImage image =
(com.aspose.imaging.fileformats.webp.WebPImage)Image.load("Animation.webp"))
{
GifOptions options = new GifOptions();
image.save("Animation.gif", options);
}
import com.aspose.imaging.Image;
import com.aspose.imaging.imageoptions.PdfOptions;
try (com.aspose.imaging.fileformats.webp.WebPImage image =
(com.aspose.imaging.fileformats.webp.WebPImage)Image.load("Animation.webp"))
{
PdfOptions options = new PdfOptions();
options.setPdfDocumentInfo(new com.aspose.imaging.fileformats.pdf.PdfDocumentInfo());
image.save("Animation.gif", options);
}
String file = "castle.wmf";
String baseFolder = "D:\\Compressed\\";
String inputFile = baseFolder + file;
String outFile = inputFile + ".wmz";
try (final Image image = Image.load(inputFile))
{
image.save(outFile, new EmfOptions(){{ setCompress(true); }});
}
String file = "example.wmz";
String baseFolder = "D:\\Compressed\\";
String inputFile = baseFolder + file;
String outFile = inputFile + ".wmf";
try (final Image image = Image.load(inputFile))
{
image.save(outFile, new WmfOptions(){{ setCompress(false); }});
}
//DICOM file format
//Digital Imaging and Communications in Medicine is the standard for the communication and management of medical imaging information. DICOM is most commonly used for storing and transmitting //medical images in medical devices such as scanners, servers, printers and picture archiving and communication systems (PACS). DICOM is used worldwide to store, exchange, and transmit //medical images.
//Various programs for Windows, macOS, and Linux can view DICOM files. DICOM uses the .DCM extension. These images can also be viewed online through certain web browsers. It is only //compatible using Chrome, Opera, Firefox, and Internet Explorer with the Google Chrome Frame extension installed.
//Why to use DICOM?
//DICOM provides a well-tested and widely accepted foundation for Medical Image Management. The advantages of using DICOM:
//Makes medical imaging information interoperable.
//Integrates image-acquisition devices, PACS, workstations, VNAs and printers from different manufacturers.
//Is actively developed and maintained to meet the evolving technologies and needs of medical imaging.
//Is free to download and use.
//Convert JPEG to DICOM
//The next code sample converts JPEG image to DICOM file format:
try (Image image = Image.load("sample.jpg"))
{
image.save("sample.dcm", new DicomOptions());
}
//Image modifications
//You can use methods of the Image class to modify source image before export. For instance, you can resize and rotate the image:
try (Image image = Image.load("sample.jpg"))
{
image.resize(300, 300);
image.rotateFlip(RotateFlipType.Rotate90FlipY);
image.save("sample.dcm", new DicomOptions());
}
//Convert multipage images to DICOM
//DICOM format supports multipage images. You can convert GIF or TIFF images to DICOM in the same way as JPEG images:
try (Image image = Image.load("animation.gif"))
{
image.save("animation.dcm", new DicomOptions());
}
//Export all DICOM pages to JPEG
//In case if you need to extract all the pages from DICOM file you can use the next code. It creates separate JPEG file for each DICOM page:
try (DicomImage image = (DicomImage)Image.load("animation.dcm"))
{
Image[] pages = image.getPages();
for (int index = 0; index < pages.length; index++)
{
Image page = pages[index];
page.save("Page "+ index +".jpeg", new JpegOptions());
}
}
// The path to the documents directory.
String dataDir = "D:/WebPImages/";
// Create an instance of image class.
try (Image image = Image.load(dataDir + "SampleImage1.bmp"))
{
// Create an instance of WebPOptions class and set properties
try (WebPOptions options = new WebPOptions())
{
options.setQuality(50);
options.setLossless(false);
image.save(dataDir+ "ExportToWebP_out.webp", options);
}
}
// The path to the documents directory.
String dataDir = "D:/WebPImages/";
// Load WebP image into the instance of image class.
try (Image image = Image.load(dataDir + "asposelogo.webp"))
{
// Save the image in WebP format.
image.save(dataDir + "ExportWebPToOtherImageFormats_out.bmp", new BmpOptions());
}
// The path to the documents directory.
String dataDir = "D:/WebPImages/";
// Load an existing WebP image into the instance of WebPImage class.
try (WebPImage image = (WebPImage)Image.load(dataDir + "asposelogo.webp"))
{
if (image.getPageCount() > 2)
{
// Access a particular frame from WebP image and cast it to Raster Image
RasterImage block = (RasterImage)image.getPages()[2];
// Save the Raster Image to a BMP image.
block.save(dataDir + "ExtractFrameFromWebPImage.bmp", new BmpOptions());
}
}
String baseFolder = "D:\\";
String inputFile = baseFolder + "sample.fodg";
String outputFile = inputFile + ".png";
try (Image image = Image.load(inputFile))
{
PngOptions options = new PngOptions();
OdgRasterizationOptions vectorOptions = new OdgRasterizationOptions();
vectorOptions.setPageSize(Size.to_SizeF(image.Size));
options.setVectorRasterizationOptions(vectorOptions);
image.save(outputFile, options);
}
import com.aspose.imaging.Image;
import com.aspose.imaging.fileformats.tiff.TiffFrame;
import com.aspose.imaging.fileformats.tiff.TiffImage;
String inputFile = "lichee.tif";
try (Image image = Image.load(inputFile))
{
String output1 = "result1.tiff";
String output2 = "result2.tiff";
image.save(output1, image.getOriginalOptions());
TiffFrame frame = ((TiffImage) image).getFrames()[0];
frame.save(output2, frame.getOriginalOptions());
}
String filePath = "Flower.png"; // specify your path
try (PngImage image = (PngImage)Image.load(filePath))
{
float opacity = image.getImageOpacity(); // opacity = 0,470798
System.out.println(opacity);
if (opacity == 0)
{
// The image is fully transparent.
}
}
import com.aspose.imaging.Image;
import com.aspose.imaging.RasterImage;
import com.aspose.imaging.Rectangle;
import com.aspose.imaging.Size;
import com.aspose.imaging.fileformats.jpeg.JpegImage;
import com.aspose.imaging.imageoptions.JpegOptions;
import com.aspose.imaging.sources.StreamSource;
String[] imagePaths = { "image1.jpg", "image2.jpg", "image3.jpg", "image4.JPG", "image5.png" };
String outputPath = "output-vertical.jpg";
// Getting resulting image size.
int newWidth = 0;
int newHeight = 0;
for (String imagePath : imagePaths)
{
try (RasterImage image = (RasterImage) Image.load(imagePath))
{
Size size = image.getSize();
newWidth = Math.max(newWidth, size.getWidth());
newHeight += size.getHeight();
}
}
// Combining images into new one.
try (JpegOptions options = new JpegOptions())
{
options.setSource(new StreamSource()); // empty
options.setQuality(100);
try (JpegImage newImage = (JpegImage) Image.create(options, newWidth, newHeight))
{
int stitchedHeight = 0;
for (String imagePath : imagePaths)
{
try(RasterImage image = (RasterImage) Image.load(imagePath))
{
Rectangle bounds = new Rectangle(0, stitchedHeight, image.getWidth(), image.getHeight());
newImage.saveArgb32Pixels(bounds, image.loadArgb32Pixels(image.getBounds()));
stitchedHeight += image.getHeight();
}
}
newImage.save(outputPath);
}
}
import com.aspose.imaging.*;
import com.aspose.imaging.fileformats.jpeg.JpegImage;
import com.aspose.imaging.imageoptions.JpegOptions;
import com.aspose.imaging.sources.FileCreateSource;
String[] imagePaths = { "image1.jpg", "image2.jpg", "image3.jpg", "image4.JPG", "image5.png" };
String outputPath = "output-horizontal.jpg";
String tempFilePath = "temp.jpg";
// Getting resulting image size.
int newWidth = 0;
int newHeight = 0;
for (String imagePath : imagePaths)
{
try (RasterImage image = (RasterImage) Image.load(imagePath))
{
Size size = image.getSize();
newWidth += size.getWidth();
newHeight = Math.max(newHeight, size.getHeight());
}
}
// Combining images into new one.
try (JpegOptions options = new JpegOptions())
{
Source tempFileSource = new FileCreateSource(tempFilePath, true);
options.setSource(tempFileSource);
options.setQuality(100);
try (JpegImage newImage = (JpegImage) Image.create(options, newWidth, newHeight))
{
int stitchedWidth = 0;
for (String imagePath : imagePaths)
{
try(RasterImage image = (RasterImage) Image.load(imagePath))
{
Rectangle bounds = new Rectangle(stitchedWidth, 0, image.getWidth(), image.getHeight());
newImage.saveArgb32Pixels(bounds, image.loadArgb32Pixels(image.getBounds()));
stitchedWidth += image.getWidth();
}
}
newImage.save(outputPath);
}
}
import com.aspose.imaging.Image;
import com.aspose.imaging.RasterImage;
import com.aspose.imaging.Rectangle;
import com.aspose.imaging.Size;
import com.aspose.imaging.fileformats.jpeg.JpegImage;
import com.aspose.imaging.imageoptions.JpegOptions;
import com.aspose.imaging.imageoptions.PdfOptions;
import com.aspose.imaging.sources.StreamSource;
String[] imagePaths = { "image1.jpg", "image2.jpg", "image3.jpg", "image4.JPG", "image5.png" };
String outputPath = "output-vertical.jpg";
// Getting resulting image size.
int newWidth = 0;
int newHeight = 0;
for (String imagePath : imagePaths)
{
try (RasterImage image = (RasterImage) Image.load(imagePath))
{
Size size = image.getSize();
newWidth = Math.max(newWidth, size.getWidth());
newHeight += size.getHeight();
}
}
// Combining images into new one.
try (JpegOptions options = new JpegOptions())
{
options.setSource(new StreamSource()); // empty
options.setQuality(100);
try (JpegImage newImage = (JpegImage) Image.create(options, newWidth, newHeight))
{
int stitchedHeight = 0;
for (String imagePath : imagePaths)
{
try(RasterImage image = (RasterImage) Image.load(imagePath))
{
Rectangle bounds = new Rectangle(0, stitchedHeight, image.getWidth(), image.getHeight());
newImage.saveArgb32Pixels(bounds, image.loadArgb32Pixels(image.getBounds()));
stitchedHeight += image.getHeight();
}
}
newImage.save(outputPath, new PdfOptions());
}
}
import com.aspose.imaging.*;
import com.aspose.imaging.fileformats.jpeg.JpegImage;
import com.aspose.imaging.imageoptions.JpegOptions;
import com.aspose.imaging.imageoptions.PdfOptions;
import com.aspose.imaging.sources.FileCreateSource;
String[] imagePaths = { "image1.jpg", "image2.jpg", "image3.jpg", "image4.JPG", "image5.png" };
String outputPath = "output-horizontal.jpg";
String tempFilePath = "temp.jpg";
// Getting resulting image size.
int newWidth = 0;
int newHeight = 0;
for (String imagePath : imagePaths)
{
try (RasterImage image = (RasterImage) Image.load(imagePath))
{
Size size = image.getSize();
newWidth += size.getWidth();
newHeight = Math.max(newHeight, size.getHeight());
}
}
// Combining images into new one.
try (JpegOptions options = new JpegOptions())
{
Source tempFileSource = new FileCreateSource(tempFilePath, true);
options.setSource(tempFileSource);
options.setQuality(100);
try (JpegImage newImage = (JpegImage) Image.create(options, newWidth, newHeight))
{
int stitchedWidth = 0;
for (String imagePath : imagePaths)
{
try(RasterImage image = (RasterImage) Image.load(imagePath))
{
Rectangle bounds = new Rectangle(stitchedWidth, 0, image.getWidth(), image.getHeight());
newImage.saveArgb32Pixels(bounds, image.loadArgb32Pixels(image.getBounds()));
stitchedWidth += image.getWidth();
}
}
newImage.save(outputPath, new PdfOptions());
}
}
import com.aspose.imaging.Image;
import com.aspose.imaging.RasterImage;
import com.aspose.imaging.Rectangle;
import com.aspose.imaging.Size;
import com.aspose.imaging.fileformats.jpeg.JpegImage;
import com.aspose.imaging.imageoptions.JpegOptions;
import com.aspose.imaging.imageoptions.PngOptions;
import com.aspose.imaging.sources.StreamSource;
String[] imagePaths = { "image1.jpg", "image2.jpg", "image3.jpg", "image4.JPG", "image5.png" };
String outputPath = "output-vertical.jpg";
// Getting resulting image size.
int newWidth = 0;
int newHeight = 0;
for (String imagePath : imagePaths)
{
try (RasterImage image = (RasterImage) Image.load(imagePath))
{
Size size = image.getSize();
newWidth = Math.max(newWidth, size.getWidth());
newHeight += size.getHeight();
}
}
// Combining images into new one.
try (JpegOptions options = new JpegOptions())
{
options.setSource(new StreamSource()); // empty
options.setQuality(100);
try (JpegImage newImage = (JpegImage) Image.create(options, newWidth, newHeight))
{
int stitchedHeight = 0;
for (String imagePath : imagePaths)
{
try(RasterImage image = (RasterImage) Image.load(imagePath))
{
Rectangle bounds = new Rectangle(0, stitchedHeight, image.getWidth(), image.getHeight());
newImage.saveArgb32Pixels(bounds, image.loadArgb32Pixels(image.getBounds()));
stitchedHeight += image.getHeight();
}
}
newImage.save(outputPath, new PngOptions());
}
}
import com.aspose.imaging.*;
import com.aspose.imaging.fileformats.jpeg.JpegImage;
import com.aspose.imaging.imageoptions.JpegOptions;
import com.aspose.imaging.imageoptions.PngOptions;
import com.aspose.imaging.sources.FileCreateSource;
String[] imagePaths = { "image1.jpg", "image2.jpg", "image3.jpg", "image4.JPG", "image5.png" };
String outputPath = "output-horizontal.jpg";
String tempFilePath = "temp.jpg";
// Getting resulting image size.
int newWidth = 0;
int newHeight = 0;
for (String imagePath : imagePaths)
{
try (RasterImage image = (RasterImage) Image.load(imagePath))
{
Size size = image.getSize();
newWidth += size.getWidth();
newHeight = Math.max(newHeight, size.getHeight());
}
}
// Combining images into new one.
try (JpegOptions options = new JpegOptions())
{
Source tempFileSource = new FileCreateSource(tempFilePath, true);
options.setSource(tempFileSource);
options.setQuality(100);
try (JpegImage newImage = (JpegImage) Image.create(options, newWidth, newHeight))
{
int stitchedWidth = 0;
for (String imagePath : imagePaths)
{
try(RasterImage image = (RasterImage) Image.load(imagePath))
{
Rectangle bounds = new Rectangle(stitchedWidth, 0, image.getWidth(), image.getHeight());
newImage.saveArgb32Pixels(bounds, image.loadArgb32Pixels(image.getBounds()));
stitchedWidth += image.getWidth();
}
}
newImage.save(outputPath, new PngOptions());
}
}
import com.aspose.imaging.Image;
import com.aspose.imaging.imageoptions.JpegOptions;
// load file to be converted
try (Image img = Image.load("photo.dng"))
{
//Apply grayscale filter to loaded image
img.grayscale();
//Save image to Jpeg format
img.save(dir + "output.jpg", new JpegOptions());
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(SupportForCMYKAndYCCKColorModesInJPEGLosslessUsingRGBProfile.class) + "ManipulatingJPEGImages/";
ByteArrayOutputStream jpegStream_cmyk = new ByteArrayOutputStream();
ByteArrayOutputStream jpegStream_ycck = new ByteArrayOutputStream();
// Save to JPEG Lossless CMYK
JpegImage image = (JpegImage)Image.load("056.jpg");
try
{
JpegOptions options = new JpegOptions();
options.setCompressionType(JpegCompressionMode.Lossless);
// Save with specified profiles
StreamSource rgbColorProfile = new StreamSource(new RandomAccessFile("eciRGB_v2.icc", "r"));
StreamSource cmykColorProfile = new StreamSource(new RandomAccessFile("ISOcoated_v2_FullGamut4.icc", "r"));
// The default profiles will be used.
options.setRgbColorProfile(rgbColorProfile);
options.setCmykColorProfile(cmykColorProfile);
// Save to Cmyk
options.setColorType(JpegCompressionColorMode.Cmyk);
image.save(jpegStream_cmyk, options);
// Save to Ycck
options.setColorType(JpegCompressionColorMode.Ycck);
image.save(jpegStream_ycck, options);
options.dispose();
}
finally
{
image.dispose();
}
// Load from JPEG Lossless CMYK
image = (JpegImage)Image.load(new ByteArrayInputStream(jpegStream_cmyk.toByteArray()));
try
{
image.save("056_cmyk_profile.png", new PngOptions());
}
finally
{
image.dispose();
}
// Load from JPEG Lossless Ycck
image = (JpegImage)Image.load(new ByteArrayInputStream(jpegStream_ycck.toByteArray()));
try
{
image.save("056_ycck_profile.png", new PngOptions());
}
finally
{
image.dispose();
}
final String dataDir = "dataDir/";
final int ImageSize = 2000;
try (ImageOptionsBase createOptions = new PngOptions())
{
createOptions.setSource(new FileCreateSource(dataDir + "temporary.png"));
createOptions.setBufferSizeHint(30); // Memory limit is 30 Mb
try (Image image = Image.create(createOptions, ImageSize, ImageSize))
{
Graphics graphics = new Graphics(image);
// You can use any graphic operations here, all of them will be performed within the established memory limit
// For example:
graphics.clear(Color.getLightSkyBlue());
graphics.drawLine(new Pen(Color.getRed(), 3f), 0, 0, image.getWidth(), image.getHeight());
}
}
// A large number of graphic operations are also supported:
final int OperationAreaSize = 10;
try (ImageOptionsBase createOptions = new PngOptions())
{
createOptions.setSource(new FileCreateSource(dataDir + "temporary.png"));
createOptions.setBufferSizeHint(30); // Memory limit is 30 Mb
try (Image image = Image.create(createOptions, ImageSize, ImageSize))
{
Graphics graphics = new Graphics(image);
graphics.beginUpdate();
graphics.clear(Color.getLightSkyBlue());
int x, y;
for (int column = 0; column * OperationAreaSize < ImageSize; column++)
{
for (int row = 0; row * OperationAreaSize < ImageSize; row++)
{
x = column * OperationAreaSize;
y = row * OperationAreaSize;
boolean reversed = (column + row) % 2 != 0;
if (reversed)
{
graphics.drawLine(
new Pen(Color.getRed()),
x + OperationAreaSize - 2,
y,
x,
y + OperationAreaSize);
}
else
{
graphics.drawLine(
new Pen(Color.getRed()),
x,
y,
x + OperationAreaSize - 2,
y + OperationAreaSize);
}
}
}
// About 40k operations will be applied here, while they do not take up too much memory
// (since they are already unloaded into the external file, and will be loaded from there one at a time)
graphics.endUpdate();
}
}
// Setting a memory limit of 10 megabytes for target loaded image
LoadOptions loadOptions = new LoadOptions();
loadOptions.setBufferSizeHint(10);
try (Image image = Image.load("Default.tiff", loadOptions))
{
image.save("Default_export.tiff", new TiffOptions(TiffExpectedFormat.Default));
}
try (Image image = Image.load("TiffCcitRle.tiff", loadOptions))
{
image.save("TiffCcitRle_export.tiff", new TiffOptions(TiffExpectedFormat.TiffCcitRle));
}
try (Image image = Image.load("TiffDeflateRgb.tiff", loadOptions))
{
image.save("TiffDeflateRgb_export.tiff", new TiffOptions(TiffExpectedFormat.TiffDeflateRgb));
}
try (Image image = Image.load("TiffJpegYCbCr.tiff", loadOptions))
{
image.save("TiffJpegYCbCr_export.tiff", new TiffOptions(TiffExpectedFormat.TiffJpegYCbCr));
}
try (Image image = Image.load("TiffLzwCmyk.tiff", loadOptions))
{
image.save("TiffLzwCmyk_export.tiff", new TiffOptions(TiffExpectedFormat.TiffLzwCmyk));
}
try (Image image = Image.load("TiffNoCompressionRgb.tiff", loadOptions))
{
image.save("TiffNoCompressionRgb_export.tiff", new TiffOptions(TiffExpectedFormat.TiffNoCompressionRgb));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment