Convert Images using Java Image Processing Library
Converting Images to Black n White and Grayscale
Sometimes you may require to convert colored images to Black n White or Grayscale for printing or archiving purposes. This article demonstrates the use of Aspose.Imaging for Java API to achieve this using two methods as stated below.
- Binarization
- Grayscaling
Binarization
In order to understand the concept of Binarization, it is important to define a Binary Image; that is a digital image that can have only two possible values for each pixel. Normally, the two colors used for a binary image are black and white though any two colors can be used. Binarization is the process of converting an image to bi-level meaning that each pixel is stored as a single bit (0 or 1) where 0 denotes the absence of color and 1 means presence of color. Aspose.Imaging for Java API currently supports two Binarization methods.
Binarization with Fixed Threshold
The following code snippet shows you how to use fixed threshold binarization can be applied to an image.
// Load an image in an instance of Image | |
try (Image image = Image.load(dataDir + "aspose-logo.jpg")) | |
{ | |
// Cast the image to RasterCachedImage and Check if image is cached | |
RasterCachedImage rasterCachedImage = (RasterCachedImage)image; | |
if (!rasterCachedImage.IsCached) | |
{ | |
// Cache image if not already cached | |
rasterCachedImage.CacheData(); | |
} | |
// Binarize image with predefined fixed threshold and Save the resultant image | |
rasterCachedImage.binarizeFixed((byte) 100); | |
rasterCachedImage.save(dataDir + "BinarizationWithFixedThreshold_out.jpg"); | |
} |
Binarization with Otsu Threshold
The following code snippet shows you how Otsu threshold binarization can be applied to an image.
// Load an image in an instance of Image | |
try (Image image = Image.load(dataDir + "aspose-logo.jpg")) | |
{ | |
// Cast the image to RasterCachedImage and Check if image is cached | |
RasterCachedImage rasterCachedImage = (RasterCachedImage) image; | |
if (!rasterCachedImage.isCached()) | |
{ | |
// Cache image if not already cached | |
rasterCachedImage.cacheData(); | |
} | |
// Binarize image with Otsu Thresholding | |
rasterCachedImage.binarizeOtsu(); | |
// Save the resultant image | |
rasterCachedImage.save(dataDir + "BinarizationWithOtsuThreshold_out.jpg"); | |
} |
Grayscaling
Gray-scaling is the process of converting a continuous-tone image to an image with discontinues gray shades. The following code snippet shows you how to use Grayscaling.
String dataDir = "/PathToImageDir/"; | |
// Load an image in an instance of Image | |
try (Image image = Image.load(dataDir + "aspose-logo.jpg")) | |
{ | |
// Cast the image to RasterCachedImage | |
RasterCachedImage rasterCachedImage = (RasterCachedImage) image; | |
// Check if image is cached | |
if (!rasterCachedImage.isCached()) { | |
// Cache image if not already cached | |
rasterCachedImage.cacheData(); | |
} | |
// Transform image to its grayscale representation | |
rasterCachedImage.grayscale(); | |
// Save the resultant image | |
rasterCachedImage.save(dataDir + "Grayscaling_out.jpg"); | |
} |
Convert Image to grayscale with Setting 16bit
Gray-scaling is the process of converting a continuous-tone image to an image with discontinues gray shades. The following code snippet shows you how to use Grayscaling with 16bits.
String dataDir = "/PathToImageDir/"; | |
// Load an image in an instance of Image | |
try (Image image = Image.load(dataDir + "aspose-logo.jpg")) | |
{ | |
// Cast the image to RasterCachedImage | |
RasterCachedImage rasterCachedImage = (RasterCachedImage) image; | |
// Check if image is cached | |
if (!rasterCachedImage.isCached()) { | |
// Cache image if not already cached | |
rasterCachedImage.cacheData(); | |
} | |
// Transform image to its grayscale representation | |
rasterCachedImage.grayscale(); | |
// Save the resultant image | |
rasterCachedImage.save(dataDir + "Grayscaling_out.jpg"); | |
} |
Convert GIF Image Layers To TIFF Image
Sometimes it is needed to extract and convert layers of a GIF Image into another raster image format to meet an application need. Aspose.Imaging API support the feature of extracting and converting layers of a GIF Image into another raster image formats. Firstly, we will create instance of image and load GIF image from the local disk, then we will get the total count of layers in the source image using Length property of GifFrameBlock class and iterate through the array of blocks. Now we will check if the block is null then ignore it else convert the block to TIFF image. The following code snippet shows you how to convert GIF image layers to TIFF image.
// Load a GIF image | |
String dataDir = "/anyDir/"; | |
try (GifImage gif = (GifImage)Image.load(dataDir + "aspose-logo.gif")) | |
{ | |
// iterate through array of blocks in the GIF image | |
IGifBlock[] blocks = gif.getBlocks(); | |
for (int i = 0; i < blocks.length; i++) | |
{ | |
// Check if it is not a gif block then ignore it | |
if (!(blocks[i] instanceof GifFrameBlock)) | |
continue; | |
// convert block to GifFrameBlock class instance | |
GifFrameBlock gifBlock = ((GifFrameBlock) (blocks[i])); | |
// Create an instance of TIFF Option class | |
TiffOptions objTiff = new TiffOptions(TiffExpectedFormat.Default); | |
// Save the GIFF block as TIFF image | |
gifBlock.save(dataDir + "asposelogo" + i + "_out.tif", objTiff); | |
} | |
} |
Converting SVG to Raster Format
See :
Converting Raster Image to PDF
See :
Converting Raster Image to Svg
See
Converting RGB color system to CMYK for Tiff file Format
Using Aspose.Imaging for Java, developers can convert RGB color system file to CMYK tiff format. This article shows how to export/convert RGB color system file to CMYK tiff format with Aspose.Imaging. Using Aspose.Imaging for Java you can load image of any format and than you can set various properties using TiffOptions class and save the image. The following code snippet shows you how to achieve this feature.
String dataDir = "/anyDir/"; | |
String sourceFilePath = "testTileDeflate.tif"; | |
String outputFilePath = "testTileDeflate Cmyk Icc.tif"; | |
TiffOptions options = new TiffOptions(TiffExpectedFormat.TiffLzwCmyk); | |
try (Image image = Image.load(sourceFilePath)) | |
{ | |
image.save(outputFilePath, options); | |
} |
Working with animation
See
Converting Open document graphics
See
Converting Corel Draw images
See Convert CDR
Converting webp images
Converting EPS images
Converting cmx images
Converting dicom images
Exporting Images
Along with a rich set of image processing routines, Aspose.Imaging provides specialized classes to convert images to other formats. Using this library, image format conversion is as simple as changing the file extension to desired format in the Image class save method and by specifying the appropriate ImageOptionsBase values. Below are some specialized classes for this purpose in imageoptions package.
It is easy to export images with Aspose.Imaging for Java API. All you need is an object of the appropriate class from imageoptions package. By using these classes, you can easily export any image created, edited or simply loaded with Aspose.Imaging for Java to any supported format. Below is an example that demonstrates this simple procedure. In the example, a GIF image is loaded by passing the file path as a parameter to the load method. It is then exported to various image formats using the save method. The examples here show how to load a GIF and save it to BMP, JPEG, PNG and finally TIFF using 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"); | |
try | |
{ | |
//Export to BMP file format using the default options | |
image.save(dataDir + "ExportImageToDifferentFormats_out.bmp" , new com.aspose.imaging.imageoptions.BmpOptions()); | |
//Export to JPEG file format using the default options | |
image.save(dataDir + "ExportImageToDifferentFormats_out.jpeg", new com.aspose.imaging.imageoptions.JpegOptions()); | |
//Export to PNG file format using the default options | |
image.save(dataDir + "ExportImageToDifferentFormats_out.png", new com.aspose.imaging.imageoptions.PngOptions()); | |
//Export to TIFF file format using the default options | |
image.save(dataDir + "ExportImageToDifferentFormats_out.tiff", new TiffOptions(TiffExpectedFormat.Default)); | |
} | |
finally | |
{ | |
image.close(); | |
} |
Convert compressed vector formats
Aspose.Imaging supports next compressed vector formats: Emz(compressed emf), Wmz(compressed wmf), Svgz(compressed svg). Supported read of these formats and export to other formats.
// 1.Export compressed formats to raster | |
String[] files = {"example.emz", "example.wmz", "example.svgz"}; | |
String baseFolder = "D:\\Compressed\\"; | |
for (String file : files) | |
{ | |
String inputFile = baseFolder + file; | |
String outFile = inputFile + ".png"; | |
try (final Image image = Image.load(inputFile)) | |
{ | |
final VectorRasterizationOptions vectorRasterizationOptions = (VectorRasterizationOptions)image.getDefaultOptions(new Object[] { Color.getWhite(), image.getWidth(), image.getHeight() }); | |
image.save(outFile, new PngOptions(){{ setVectorRasterizationOptions(vectorRasterizationOptions); }}); | |
} | |
} | |
// 2.Export Emz to Emf | |
String file = "example.emz"; | |
String baseFolder = "D:\\Compressed\\"; | |
String inputFile = baseFolder + file; | |
String outFile = inputFile + ".emf"; | |
try (final Image image = Image.load(inputFile)) | |
{ | |
final VectorRasterizationOptions vectorRasterizationOptions = new EmfRasterizationOptions() {{ setPageSize(Size.to_SizeF(image.getSize())); }}; | |
image.save(outFile, new EmfOptions(){{ setVectorRasterizationOptions(vectorRasterizationOptions); }}); | |
} | |
// 3.Export Wmz to Wmf | |
String file = "example.wmz"; | |
String baseFolder = "D:\\Compressed\\"; | |
String inputFile = baseFolder + file; | |
String outFile = inputFile + ".wmf"; | |
try (final Image image = Image.load(inputFile)) | |
{ | |
final VectorRasterizationOptions vectorRasterizationOptions = new WmfRasterizationOptions() {{ setPageSize(Size.to_SizeF(image.getSize())); }}; | |
image.save(outFile, new WmfOptions(){{ setVectorRasterizationOptions(vectorRasterizationOptions); }}); | |
} | |
// 4.Export Svgz to Svg | |
String file = "example.svgz"; | |
String baseFolder = "D:\\Compressed\\"; | |
String inputFile = baseFolder + file; | |
String outFile = inputFile + ".svg"; | |
try (final Image image = Image.load(inputFile)) | |
{ | |
final VectorRasterizationOptions vectorRasterizationOptions = new SvgRasterizationOptions() {{ setPageSize(Size.to_SizeF(image.getSize())); }}; | |
image.save(outFile, new SvgOptions(){{ setVectorRasterizationOptions(vectorRasterizationOptions); }}); | |
} | |
// 5.Export Emf to Emz | |
String file = "input.emf"; | |
String baseFolder = "D:\\Compressed\\"; | |
String inputFile = baseFolder + file; | |
String outFile = inputFile + ".emz"; | |
try (final Image image = Image.load(inputFile)) | |
{ | |
final VectorRasterizationOptions vectorRasterizationOptions = new EmfRasterizationOptions() {{ setPageSize(Size.to_SizeF(image.getSize())); }}; | |
image.save(outFile, new EmfOptions(){{ setVectorRasterizationOptions(vectorRasterizationOptions); setCompress(true); }}); | |
} | |
// 6.Export Wmf to Wmz | |
String file = "castle.wmf"; | |
String baseFolder = "D:\\Compressed\\"; | |
String inputFile = baseFolder + file; | |
String outFile = inputFile + ".wmz"; | |
try (final Image image = Image.load(inputFile)) | |
{ | |
final VectorRasterizationOptions vectorRasterizationOptions = new WmfRasterizationOptions() {{ setPageSize(Size.to_SizeF(image.getSize())); }}; | |
image.save(outFile, new EmfOptions(){{ setVectorRasterizationOptions(vectorRasterizationOptions); setCompress(true); }}); | |
} | |
// 7.Export Svg to Svgz | |
String file = "juanmontoya_lingerie.svg"; | |
String baseFolder = "D:\\Compressed\\"; | |
String inputFile = baseFolder + file; | |
String outFile = inputFile + ".svgz"; | |
try (final Image image = Image.load(inputFile)) | |
{ | |
final VectorRasterizationOptions vectorRasterizationOptions = new SvgRasterizationOptions() {{ setPageSize(Size.to_SizeF(image.getSize())); }}; | |
image.save(outFile, new SvgOptions(){{ setVectorRasterizationOptions(vectorRasterizationOptions); setCompress(true); }}); | |
} |
Combining Images
This example uses Graphics class and shows how to combine two or more images into a single complete image.To demonstrate the operation, the example creates a new Image canvas in JPEG format and draw images on the canvas surface using Draw Image method exposed by Graphics class. Using Graphics class two or more images can be combine in such a way that the resultant image will look as a complete image with no space between the image parts and no pages. The canvas size must be equal to the size of resultant image. Following is the code demonstration that shows how to use Draw Image method of the Graphics class to combine images in a single image.
// The path to the documents directory. | |
String dataDir = "D:\\DataDir\\"; | |
// Create an instance of JpegOptions and set its various properties | |
com.aspose.imaging.imageoptions.JpegOptions imageOptions = new com.aspose.imaging.imageoptions.JpegOptions(); | |
try | |
{ | |
// Create an instance of FileCreateSource and assign it to Source | |
// property | |
imageOptions.setSource(new com.aspose.imaging.sources.FileCreateSource(dataDir + "two_images_result_out.jpeg", false)); | |
// Create an instance of Image | |
com.aspose.imaging.Image image = com.aspose.imaging.Image.create(imageOptions, 600, 600); | |
try | |
{ | |
// Create and initialize an instance of Graphics | |
com.aspose.imaging.Graphics graphics = new com.aspose.imaging.Graphics(image); | |
// Clear the image surface with white color | |
graphics.clear(com.aspose.imaging.Color.getWhite()); | |
// Draw Image | |
try (Image tmp = com.aspose.imaging.Image.load(dataDir + "sample_1.bmp")) | |
{ | |
graphics.drawImage(tmp, 0, 0, 600, 300); | |
} | |
try (Image tmp = com.aspose.imaging.Image.load(dataDir + "File1.bmp")) | |
{ | |
graphics.drawImage(tmp, 0, 300, 600, 300); | |
} | |
// Call save method to save the resultant image. | |
image.save(); | |
} | |
finally | |
{ | |
image.close(); | |
} | |
} | |
finally | |
{ | |
imageOptions.close(); | |
} |
Expand and Crop Images
Aspose.Imaging API allows you to expand or crop an image during image conversion process. Developer needs to create a rectangle with X and Y coordinates and specify the width and height of the rectangle box. The X,Y and Width, Height of rectangle will depict the expansion or cropping of the loaded image. If it is required to expand or crop the image during image conversion, perform the following steps:
- Create an instance of RasterImage class and load the existing image.
- Create an Instance of ImageOptionsBase class.
- Create an instance of Rectangle class and initialize the X,Y and Width, Height of the rectangle
- Call Save method of the RasterImage class while passing output file name, image options and the rectangle object as parameters.
// The path to the documents directory. | |
String dataDir = "D:/DataDir/"; | |
// Load an image in an instance of Image and Setting for image data to be cashed | |
try (RasterImage rasterImage = (RasterImage)Image.load(dataDir + "aspose-logo.jpg")) | |
{ | |
rasterImage.cacheData(); | |
// Create an instance of Rectangle class and define X,Y and Width, height of the rectangle, and Save output image | |
Rectangle destRect = new Rectangle(-200, -200, 300, 300); | |
rasterImage.save(dataDir + "Grayscaling_out.jpg", new JpegOptions(), destRect); | |
} |
Read and Write XMP Data To Images
XMP (Extensible Metadata Platform) is an ISO standard. XMP standardizes a data model, a serialization format and core properties for the definition and processing of extensible metadata. It also provides guidelines for embedding XMP information into popular image such as JPEG, without breaking their readability by applications that do not support XMP. Using Aspose.Imaging for Java API developers can read or write XMP metadata to images. This article demonstrates how XMP metadata can be read from image and write XMP metadata to images.
Create XMP Metadata, Write It And Read From File
The release of Aspose.Imaging for Java 3.3.0 contains the Xmp namespace. With the help of Xmp namespace developer can create XMP metadata object and write it to an image. The following code snippet shows you how to use the XmpHeaderPi, XmpTrailerPi, XmpMeta, XmpPacketWrapper, PhotoshopPackage and DublinCorePackage packages contained in Xmp namespace.
import com.aspose.imaging.Rectangle; | |
import com.aspose.imaging.fileformats.tiff.TiffFrame; | |
import com.aspose.imaging.fileformats.tiff.TiffImage; | |
import com.aspose.imaging.fileformats.tiff.enums.TiffExpectedFormat; | |
import com.aspose.imaging.fileformats.tiff.enums.TiffPhotometrics; | |
import com.aspose.imaging.imageoptions.TiffOptions; | |
import com.aspose.imaging.xmp.*; | |
import com.aspose.imaging.xmp.schemas.dublincore.DublinCorePackage; | |
import com.aspose.imaging.xmp.schemas.photoshop.ColorMode; | |
import com.aspose.imaging.xmp.schemas.photoshop.PhotoshopPackage; | |
// Specify the size of image by defining a Rectangle | |
Rectangle rect = new Rectangle(0, 0, 100, 200); | |
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.TiffJpegRgb); | |
tiffOptions.setPhotometric(TiffPhotometrics.MinIsBlack); | |
tiffOptions.setBitsPerSample(new int[] { 8 }); | |
// create the brand new image just for sample purposes | |
TiffImage image = new TiffImage(new TiffFrame(tiffOptions, rect.getWidth(), rect.getHeight())); | |
try | |
{ | |
// create an instance of XMP-Header | |
XmpHeaderPi xmpHeader = new XmpHeaderPi(UUID.randomUUID().toString()); | |
// create an instance of Xmp-TrailerPi | |
XmpTrailerPi xmpTrailer = new XmpTrailerPi(true); | |
// create an instance of XMPmeta class to set different attributes | |
XmpMeta xmpMeta = new XmpMeta(); | |
xmpMeta.addAttribute("Author", "Mr Smith"); | |
xmpMeta.addAttribute("Description", "The fake metadata value"); | |
// create an instance of XmpPacketWrapper that contains all metadata | |
XmpPacketWrapper xmpData = new XmpPacketWrapper(xmpHeader, xmpTrailer, xmpMeta); | |
// create an instance of Photoshop package and set photoshop attributes | |
PhotoshopPackage photoshopPackage = new PhotoshopPackage(); | |
photoshopPackage.setCity("London"); | |
photoshopPackage.setCountry("England"); | |
photoshopPackage.setColorMode(ColorMode.Rgb); | |
photoshopPackage.setCreatedDate(new Date()); | |
// add photoshop package into XMP metadata | |
xmpData.addPackage(photoshopPackage); | |
// create an instance of DublinCore package and set dublinCore attributes | |
DublinCorePackage dublinCorePackage = new DublinCorePackage(); | |
dublinCorePackage.setAuthor("Charles Bukowski"); | |
dublinCorePackage.setTitle("Confessions of a Man Insane Enough to Live With the Beasts"); | |
dublinCorePackage.addValue("dc:movie", "Barfly"); | |
// add dublinCore Package into XMP metadata | |
xmpData.addPackage(dublinCorePackage); | |
// update XMP metadata into image | |
image.setXmpData(xmpData); | |
try (ByteArrayOutputStream mem = new ByteArrayOutputStream()) | |
{ | |
// Save image on the disk or in memory stream | |
image.save(mem); | |
// Load the image from memory stream or from disk to read/get the metadata | |
try (TiffImage img = (TiffImage)Image.load(new ByteArrayInputStream(mem.toByteArray()))) | |
{ | |
// Getting the XMP metadata | |
XmpPacketWrapper imgXmpData = img.getXmpData(); | |
for (XmpPackage pkg : imgXmpData.getPackages()) | |
{ | |
// Use package data ... | |
} | |
} | |
} | |
} | |
finally | |
{ | |
image.close(); | |
} |
Export Images in Multi Threaded Environment
Aspose.Imaging for Java now supports converting images in multi threaded environment. Aspose.Imaging for Java ensure the optimized performance of operations during execution of code in multi-threaded environment. All imaging option classes (e.g. BmpOptions, TiffOptions, JpegOptions, etc.) in the Aspose.Imaging for Java now implement Closeable interface. Therefore it is a must that developer properly dispose off the imaging options class object in case Source property is set. Following code snippet demonstrates the said functionality.
// Create temporary image. | |
java.io.File tmp = java.io.File.createTempFile("image", "tes"); | |
// Delete the file. This statement should execute to make it sure that resource is properly disposed off. | |
tmp.deleteOnExit(); | |
// Path & name of existing image. | |
String imageDataPath = tmp.getAbsolutePath(); | |
// Create the stream of the existing image file. | |
java.io.InputStream fileStream = new java.io.FileInputStream(tmp); | |
try | |
{ | |
// Create an instance of BMP image option class. | |
com.aspose.imaging.imageoptions.BmpOptions bmpOptions = new com.aspose.imaging.imageoptions.BmpOptions(); | |
try | |
{ | |
bmpOptions.setBitsPerPixel(32); | |
// Set the source property of the imaging option class object. | |
bmpOptions.setSource(new com.aspose.imaging.sources.StreamSource(fileStream)); | |
// Do processing. | |
// Following is the sample processing on the image. Un-comment to use it. | |
// com.aspose.imaging.RasterImage image = (com.aspose.imaging.RasterImage)com.aspose.imaging.Image.create(bmpOptions, 10, 10); | |
// try | |
// { | |
// com.aspose.imaging.Color[] pixels = new com.aspose.imaging.Color[4]; | |
// for (int i = 0; i < 4; ++i) | |
// { | |
// pixels[i] = com.aspose.imaging.Color.fromArgb(40, 30, 20, 10); | |
// } | |
// image.savePixels(new com.aspose.imaging.Rectangle(0, 0, 2, 2), pixels); | |
// image.save(imageDataPath); | |
//} | |
//finally | |
//{ | |
// This statement is in the final block because in any case this statement should execute to make it sure that resource is properly closed. | |
// image.close(); | |
//} | |
} | |
finally | |
{ | |
// This statement is in the final block because in any case this statement should execute to make it sure that resource is properly closed. | |
bmpOptions.close(); | |
} | |
} | |
finally | |
{ | |
// This statement is in the final block because in any case this statement should execute to make it sure that resource is properly disposed off. | |
fileStream.close(); | |
fileStream = null; | |
} |
Aspose.Imaging now supports SyncRoot property while working in multi-threaded environment. Developer can use this property to synchronize access to the source stream. Following code snippet demonstrates how the SyncRoot property can be used.
// 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(); | |
} |