Converting Images
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.PSD for .NET 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.PSD for .NET 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.
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET | |
string sourceFile = dataDir + @"sample.psd"; | |
string destName = dataDir + @"BinarizationWithFixedThreshold_out.jpg"; | |
// Load an image | |
using (Image image = Image.Load(sourceFile)) | |
{ | |
// 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(100); | |
rasterCachedImage.Save(destName, new JpegOptions()); | |
} |
Binarization with Otsu Threshold
The following code snippet shows you how Otsu threshold binarization can be applied to an image.
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET | |
string sourceFile = dataDir + @"sample.psd"; | |
string destName = dataDir + @"BinarizationWithOtsuThreshold_out.jpg"; | |
// Load an image | |
using (Image image = Image.Load(sourceFile)) | |
{ | |
// 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 and Save the resultant image | |
rasterCachedImage.BinarizeOtsu(); | |
rasterCachedImage.Save(destName, new JpegOptions()); | |
} |
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.
Convert GIF Image Layers To TIFF Image
Sometimes it is needed to extract and convert layers of a PSD Image into another raster image format to meet an application need. Aspose.PSD API supports the feature of extracting and converting layers of a PSD Image into another raster image format. Firstly, we will create an instance of image and load PSD image from the local disk, then we will iterate each layer in the Layer property. Then we will convert the block to TIFF image. The following code snippet shows you how to convert PSD image layers to TIFF images.
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET | |
string sourceFile = dataDir + @"sample.psd"; | |
string destName = dataDir + @"output"; | |
// Load a PSD image and Convert the image's layers to Tiff images. | |
using (PsdImage image = (PsdImage)Image.Load(sourceFile)) | |
{ | |
// Iterate through array of PSD layers | |
for (int i = 0; i < image.Layers.Length; i++) | |
{ | |
// Get PSD layer. | |
Layer layer = image.Layers[i]; | |
// Create an instance of TIFF Option class and Save the PSD layer as TIFF image | |
TiffOptions objTiff = new TiffOptions(TiffExpectedFormat.TiffDeflateRgb); | |
layer.Save("output" + i + "_out.tif", objTiff); | |
} | |
} |
Converting CMYK PSD to CMYK TIFF
Using Aspose.PSD for .NET, developers can convert CMYK PSD file to CMYK tiff format. This article shows how to export/convert CMYK PSD file to CMYK tiff format with Aspose.PSD. Using Aspose.PSD for .NET you can load PSD images and then you can set various properties using TiffOptions class and save or export the image. The following code snippet shows you how to achieve this feature.
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET | |
string sourceFile = dataDir + @"sample.psd"; | |
string destName = dataDir + @"output.tiff"; | |
using (Image image = Image.Load(sourceFile)) | |
{ | |
image.Save(destName, new TiffOptions(TiffExpectedFormat.TiffLzwCmyk)); | |
} |
Exporting Images
Along with a rich set of image processing routines, Aspose.PSD provides specialized classes to convert PSD file formats to other formats. Using this library, PSD images conversion is very simple and intuitive. Below are some specialized classes for this purpose in ImageOptions namespace.
It is easy to export PSD images with Aspose.PSD for .NET API. All you need is an object of the appropriate class from ImageOptions namespace. By using these classes, you can easily export any image created, edited or simply loaded with Aspose.PSD for .NET to any supported format.
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 PsdImage and draws images on the canvas surface using Draw Image method exposed by Graphics class. Using Graphics class two or more images can be combined 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 the resultant image. Following is the code demonstration that shows how to use DrawImage method of the Graphics class to combine images in a single image.
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET | |
// Create an instance of PsdOptions and set its various properties | |
PsdOptions imageOptions = new PsdOptions(); | |
// Create an instance of FileCreateSource and assign it to Source property | |
imageOptions.Source = new FileCreateSource(dataDir + "Two_images_result_out.psd", false); | |
// Create an instance of Image and define canvas size | |
using (var image = Image.Create(imageOptions, 600, 600)) | |
{ | |
// Create and initialize an instance of Graphics, Clear the image surface with white color and Draw Image | |
var graphics = new Graphics(image); | |
graphics.Clear(Color.White); | |
graphics.DrawImage(Image.Load(dataDir + "example1.psd"), 0, 0, 300, 600); | |
graphics.DrawImage(Image.Load(dataDir + "example2.psd"), 300, 0, 300, 600); | |
image.Save(); | |
} |
Expand and Crop Images
Aspose.PSD 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 ImageOption 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.
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET | |
string sourceFile = dataDir + @"example1.psd"; | |
string destName = dataDir + @"jpeg_out.jpg"; | |
// Load an image in an instance of Image and Setting for image data to be cashed | |
using (RasterImage rasterImage = (RasterImage)Image.Load(sourceFile)) | |
{ | |
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 { X = -200, Y = -200, Width = 300, Height = 300 }; | |
rasterImage.Save(destName, 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 a popular image such as JPEG, without breaking their readability by applications that do not support XMP. Using Aspose.PSD for .NET API developers can read or write XMP metadata to images. This article demonstrates how XMP metadata can be read from an image and write XMP metadata to images.
Create XMP Metadata, Write It And Read From File
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.
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET | |
// Specify the size of image by defining a Rectangle | |
Rectangle rect = new Rectangle(0, 0, 100, 200); | |
// Create the brand new image just for sample purposes | |
using (var image = new PsdImage(rect.Width, rect.Height)) | |
{ | |
// Create an instance of XMP-Header | |
XmpHeaderPi xmpHeader = new XmpHeaderPi(Guid.NewGuid().ToString()); | |
// Create an instance of Xmp-TrailerPi, XMPmeta class to set different attributes | |
XmpTrailerPi xmpTrailer = new XmpTrailerPi(true); | |
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); | |
photoshopPackage.SetCreatedDate(DateTime.UtcNow); | |
// 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("Mudassir Fayyaz"); | |
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); | |
using (var ms = new MemoryStream()) | |
{ | |
// Update XMP metadata into image and Save image on the disk or in memory stream | |
image.XmpData = xmpData; | |
image.Save(ms); | |
image.Save(dataDir + "ee.psd"); | |
ms.Seek(0, System.IO.SeekOrigin.Begin); | |
// Load the image from memory stream or from disk to read/get the metadata | |
using (var img = (PsdImage)Image.Load(ms)) | |
{ | |
// Getting the XMP metadata | |
XmpPacketWrapper imgXmpData = img.XmpData; | |
foreach (XmpPackage package in imgXmpData.Packages) | |
{ | |
// Use package data ... | |
} | |
} | |
} | |
} |
Export Images in Multi Threaded Environment
Aspose.PSD for .NET now supports converting images in multi-threaded environment. Aspose.PSD for .NET ensures the optimized performance of operations during execution of code in a multi-threaded environment. All image option classes (e.g. BmpOptions, TiffOptions, JpegOptions, etc.) in the Aspose.PSD for .NET implement IDisposable interface. Therefore it is a must that developer properly dispose off the image options class object in case Source property is set. Following code snippet demonstrates the said functionality.
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET | |
string imageDataPath = dataDir + @"sample.psd"; | |
try | |
{ | |
// Create the stream of the existing image file. | |
using (System.IO.FileStream fileStream = System.IO.File.Create(imageDataPath)) | |
{ | |
// Create an instance of PSD image option class. | |
using (PsdOptions psdOptions = new PsdOptions()) | |
{ | |
// Set the source property of the imaging option class object. | |
psdOptions.Source = new Sources.StreamSource(fileStream); | |
// DO PROCESSING. | |
// Following is the sample processing on the image. Un-comment to use it. | |
//using (RasterImage image = (RasterImage)Image.Create(psdOptions, 10, 10)) | |
//{ | |
// Color[] pixels = new Color[4]; | |
// for (int i = 0; i < 4; ++i) | |
// { | |
// pixels[i] = Color.FromArgb(40, 30, 20, 10); | |
// } | |
// image.SavePixels(new Rectangle(0, 0, 2, 2), pixels); | |
// image.Save(); | |
//} | |
} | |
} | |
} | |
finally | |
{ | |
// Delete the file. 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. | |
System.IO.File.Delete(imageDataPath); | |
} |
Aspose.PSD now supports SyncRoot property while working in a 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.
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET | |
// Create an instance of Memory stream class. | |
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) | |
{ | |
// Create an instance of Stream container class and assign memory stream object. | |
using (StreamContainer streamContainer = new StreamContainer(memoryStream)) | |
{ | |
// check if the access to the stream source is synchronized. | |
lock (streamContainer.SyncRoot) | |
{ | |
// do work | |
// now access to source MemoryStream is synchronized | |
} | |
} | |
} |