Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save aspose-imaging/8c9bd83e0d07145ba0c1 to your computer and use it in GitHub Desktop.
Save aspose-imaging/8c9bd83e0d07145ba0c1 to your computer and use it in GitHub Desktop.
This Gist contains code snippets of examples for Aspose.Imaging for Java.
// 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");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load an image in an instance of Image
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();
}
// Binarize image with pre defined fixed threshold
rasterCachedImage.binarizeFixed((byte) 100);
// Save the resultant image
rasterCachedImage.save(dataDir + "BinarizationWithFixedThreshold_out.jpg");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load an image in an instance of Image
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();
}
// Binarize image with Otsu Thresholding
rasterCachedImage.binarizeOtsu();
// Save the resultant image
rasterCachedImage.save(dataDir + "BinarizationWithOtsuThreshold_out.jpg");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String dataDir = Utils.getSharedDataDir(BMPToPDF.class) + "ConvertingImages/";
String outputFile = "result.pdf";
BmpImage image = (BmpImage)Image.load(dataDir);
try
{
PdfOptions exportOptions = new PdfOptions();
exportOptions.setPdfDocumentInfo(new PdfDocumentInfo());
image.save(outputFile, exportOptions);
}
finally
{
image.close();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load a GIF image
Image objImage = Image.load(dataDir + "aspose-logo.gif");
// Convert the image to GIF image
GifImage gif = (GifImage) objImage;
// iterate through arry of blocks in the GIF image
for (int i = 0; i < gif.getBlocks().length; i++) {
// convert block to GifFrameBlock class instance
GifFrameBlock gifBlock = ((GifFrameBlock) (gif.getBlocks()[i]));
// Check if gif block is then ignore it
if (gifBlock == null) {
continue;
}
// 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);
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
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.dispose();
}
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load the image
SvgImage image = (SvgImage)Image.load(dataDir + "aspose-logo.Svg");
// Create an instance of PNG options
PngOptions pngOptions = new PngOptions();
// Save the results to disk
image.save(dataDir + "ConvertingSVGToRasterImages_out.png", pngOptions);
}
// 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);
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// 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 disposed off.
// image.dispose();
//}
}
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.
bmpOptions.dispose();
}
}
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;
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String dataDir = Utils.getSharedDataDir(Grayscaling.class) + "ConvertingImages/";
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");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
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();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
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();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// 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);
// create the brand new image just for sample purposes
TiffImage image = new TiffImage(new TiffFrame(tiffOptions, rect.getWidth(), rect.getHeight()));
// create an instance of XMP-Header
XmpHeaderPi xmpHeader = new XmpHeaderPi();
xmpHeader.setGuid(dataDir);
// 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 instacne of Photoshop package and set photoshop attributes
PhotoshopPackage photoshopPackage = new PhotoshopPackage();
photoshopPackage.setCity("London");
photoshopPackage.setCountry("England");
photoshopPackage.setColorMode(ColorMode.Rgb);
// add photoshop package into XMP metadata
xmpData.addPackage(photoshopPackage);
// create an instacne 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);
MemoryStream ms = new MemoryStream();
// update XMP metadata into image
image.setXmpData(xmpData);
// Save image on the disk or in memory stream
image.save();
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String sourceFilePath = "testTileDeflate.tif";
String outputFilePath = "testTileDeflate Cmyk.tif";
TiffOptions options = new TiffOptions(TiffExpectedFormat.TiffLzwCmyk);
Image image = Image.load(sourceFilePath);
{
image.save(outputFilePath, options);
}
{
image.dispose();
}
// 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();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String[] files = new String[] {"example.odg", "example1.odg"};
String folder = "C:\\Temp\\";
final MetafileRasterizationOptions rasterizationOptions = new MetafileRasterizationOptions();
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();
}
}
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// 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);
}
// 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 + "BinarizationwithFixedThreshold_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 predefined fixed threshold.
image.binarizeFixed((byte) 100);
// 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 + "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
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);
// 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 (of type Gif) in an instance of Image class
com.aspose.imaging.Image image = com.aspose.imaging.Image.load(dataDir + "sample.gif");
//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));
// Display Status.
System.out.println("Image exported to BMP, JPG, PNG and TIFF formats successfully!");
// 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);
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
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);
// 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);
// 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"));
//Creates an instance of Image
com.aspose.imaging.Image image = com.aspose.imaging.Image.create(createOptions,500,500);
image.save();
// Display Status.
System.out.println("Image created successfully!");
// 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());
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//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");
//Print message
System.out.println("Image is loaded successfully.");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Create an Image Object and open an existing file using the Stream
// Object
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();
}
// 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.save("SavingtoDisk_out.bmp");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
java.io.OutputStream os = new java.io.FileOutputStream("C:\\SavingtoStream_out.bmp");
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);
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
//Create an instance of Image and load an existing image.
Image image= Image.load(dataDir + "sample.bmp");
//Create and initialize an instance of Graphics class.
Graphics graphics=new Graphics(image);
//Creates an instance of Font
Font font = new Font("Times New Roman", 16, FontStyle.Bold);
//Create an instance of SolidBrush and set its various properties.
SolidBrush brush = new SolidBrush();
brush.setColor(Color.getBlack());
brush.setOpacity(100);
//Draw a String using the SolidBrush object and Font, at specific Point.
graphics.drawString("Aspose.Imaging for .Net", font, brush, new PointF(image.getWidth()-100, image.getHeight()-100));
// save the image with changes
image.save(dataDir + "AddWatermarkToImage_out.bmp");
// Display Status.
System.out.println("Watermark added successfully!");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
com.aspose.imaging.imageoptions.JpegOptions ImageOptions = new com.aspose.imaging.imageoptions.JpegOptions();
// Create an instance of FileCreateSource and assign it to Source
// property
ImageOptions.setSource(
new com.aspose.imaging.sources.FileCreateSource(dataDir + "two_images_result.jpeg", false));
// Create an instance of Image
com.aspose.imaging.Image image = com.aspose.imaging.Image.create(ImageOptions, 600, 600);
// 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
graphics.drawImage(com.aspose.imaging.Image.load(dataDir + "aspose-logo.jpg"), 0, 0, 600, 300);
// Call save method to save the resultant image.
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 TiffImage and load the copied destination image
TiffImage image1 = (TiffImage) com.aspose.imaging.Image.load(dataDir + "TestDemo.tif");
// Create an instance of TiffImage and load the source image
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.
image1.save();
// Display Status.
System.out.println("Concatenation of TIF files done successfully!");
// 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");
// 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 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));
// Save all changes.
image.save(dataDir + "DrawingusingGraphics_out.bmp");
//Print message
System.out.println("Image drawn successfully. Check output file.");
// 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!");
// 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();
}
// 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();
}
}
// 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
// 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();
}
// 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());
// 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
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++;
}
// 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());
// 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");
// 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
metaImage.crop(leftShift, rightShift, topShift, bottomShift);
// Save the result in PNG format
metaImage.save(dataDir + "CropbyShifts_out.png", new PngOptions());
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
Image image = Image.load(dataDir + "picture1.emf", new MetafileLoadOptions(true));
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.dispose();
}
// 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;
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
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.getName(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.getName(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.dispose();
}
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String path = dataDir+"TestEmfPlusFigures.emf";
EmfImage image = (EmfImage)Image.load(path);
try
{
image.save(path + ".emf", new EmfOptions());
}
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+"TestEmfBezier.emf";
EmfImage image = (EmfImage)Image.load(path);
try
{
image.save(path + ".emf", new EmfOptions());
}
finally
{
image.dispose();
}
// 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
EmfMetafileImage image = (EmfMetafileImage) Image.load(dataDir + "Sample1.emf");
try {
// Create an instance of Graphics2D by calling
// EmfMetafileImage.getWatermarkDrawer
java.awt.Graphics2D drawer = image.getWatermarkDrawer();
// Creates an instance of Font and initialize it with font name,
// style and size
java.awt.Font font = new java.awt.Font("Times New Roman", FontStyle.Bold, 32);
// Set font to the instance of Graphics2D
drawer.setFont(font);
// Set the Paint attribute for the Graphics2D context with an
// instance of Color
drawer.setPaint(new java.awt.Color(0, 0, 255, 127));
// Create an instance of Rectangle2D by getting the string bounds
java.awt.geom.Rectangle2D rect = font.getStringBounds("This is the custom", drawer.getFontRenderContext());
// Estimate the X & Y positions where watermark will render on image
float posx = (float) (image.getWidth() - rect.getWidth()) / 2;
float posy = (float) (image.getHeight() - rect.getHeight()) / 2;
// Draw watermark on the image
drawer.drawString("This is the custom", posx, posy);
drawer.drawString("watermark string!", posx, posy + 30);
// Save the result in raster image format
image.save(dataDir + "WatermarkMetafiles_out.png", new PngOptions());
} finally {
// Dispose image
image.dispose();
}
// 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);
// 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();
}
// 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");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String dataDir = Utils.getSharedDataDir(SupportForReplacingMissingFonts.class) + "ModifyingImages/";
FontSettings.setDefaultFontName("Comic Sans MS");
//String dir = "C:\\IMAGINGNET-2973_example\\";
String[] files = new String[] { "missing-font.emf", "missing-font.odg", "missing-font.svg", "missing-font.wmf" };
VectorRasterizationOptions[] options = new VectorRasterizationOptions[] { new EmfRasterizationOptions(), new MetafileRasterizationOptions(), 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();
}
// 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);
// 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();
}
}
// 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.");
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
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);
Image image = Image.load(dataDir);
final 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(outFileName, pdfOptions);
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String inputFileName = dataDir + "sample.wmf";
String outFileName = dataDir + "ConvertingWMFtoPNG_out.png";
Image image = Image.load(dataDir);
try {
// Calculate new height
double k = (image.getWidth() * 1.00) / image.getHeight();
// Create an instance of EmfRasterizationOptions class and define
EmfRasterizationOptions emf = new EmfRasterizationOptions();
emf.setPageWidth(400);
emf.setPageHeight((int) Math.round(400 / k));
emf.setBorderX(5);
emf.setBorderY(10);
emf.setBackgroundColor(Color.getWhiteSmoke());
PngOptions 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(outFileName, options);
} finally {
image.dispose();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String inputFileName = dataDir + "sample.wmf";
// Path & Name of output file
String outputFileName = dataDir + "ConvertingWMFToSVG_out.svg";
// Create an instance of Image class by loading an existing WMF image.
Image image = Image.load(inputFileName);
// Create an instance of EmfRasterizationOptions class.
final EmfRasterizationOptions emfRasterizationOptions = new EmfRasterizationOptions();
emfRasterizationOptions.setPageWidth(image.getWidth());
emfRasterizationOptions.setPageHeight(image.getHeight());
image.save(outputFileName, emfRasterizationOptions);
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
String inputFileName = dataDir + "sample.wmf";
String outFileName = dataDir + "ConvertingWMFtoWebp_out.webp";
// Load an existing WMF image
Image image = Image.load(dataDir);
try {
// Calculate new height
double k = (image.getWidth() * 1.00) / image.getHeight();
// Create an instance of EmfRasterizationOptions class and define
// settings
EmfRasterizationOptions emf = new EmfRasterizationOptions();
emf.setPageWidth(400);
emf.setPageHeight((int) Math.round(400 / k));
emf.setBorderX(5);
emf.setBorderY(10);
emf.setBackgroundColor(Color.getWhiteSmoke());
// Create an instance of WebPOptions class and provide rasterization
// option
ImageOptionsBase options = new WebPOptions();
options.setVectorRasterizationOptions(emf);
// 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();
}
// For complete examples and data files, please go to https://github.com/Muhammad-Adnan-Ahmad/Aspose.Imaging-for-Java
// Load an existing WMF image
Image image = Image.load(dataDir);
try {
// Create an instance of EmfRasterizationOptions class and set
// different properties
EmfRasterizationOptions emf = new EmfRasterizationOptions();
emf.setPageWidth(2000);
emf.setPageHeight(2000);
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(outFileName, 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 existing WMF image
Image image = Image.load(dataDir);
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(outFileName, options);
} finally {
image.dispose();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment