Manipulating PNG Images

Specifying Transparency for PNG Images

One of the advantages of saving images in PNG format is that PNG can have transparent background. Aspose.Imaging for .NET provides the feature for specifying transparency for the PngImage & RasterImage classes as demonstrated in the below section. Aspose.Imaging for .NET API can be used to set any color as transparent while creating new PNG images or converting existing images to PNG format. For this purposes, the Aspose.Imaging for .NET API has exposed TransparentColor property and PngColorType enumeration that can be set to specify any color to be rendered as transparent in the newly created PNG image. The below provided code snippet demonstrates how to convert an existing BMP image to PNG format by creating a PNG image from scratch while specifying the desired color as transparent.

using Aspose.Imaging;
using Aspose.Imaging.Brushes;
using Aspose.Imaging.FileFormats.Bmp;
using Aspose.Imaging.FileFormats.Core.VectorPaths;
using Aspose.Imaging.FileFormats.Emf;
using Aspose.Imaging.FileFormats.Emf.Emf.Consts;
using Aspose.Imaging.FileFormats.Emf.Graphics;
using Aspose.Imaging.FileFormats.Gif;
using Aspose.Imaging.FileFormats.Gif.Blocks;
using Aspose.Imaging.FileFormats.Png;
using Aspose.Imaging.FileFormats.Tiff;
using Aspose.Imaging.FileFormats.Tiff.Enums;
using Aspose.Imaging.FileFormats.Tiff.PathResources;
using Aspose.Imaging.FileFormats.Webp;
using Aspose.Imaging.FileFormats.Wmf;
using Aspose.Imaging.FileFormats.Wmf.Graphics;
using Aspose.Imaging.ImageOptions;
using Aspose.Imaging.Sources;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
string templatesFolder = @"c:\Users\USER\Downloads\templates\";
string dataDir = templatesFolder;
string fileName = Path.Combine(dataDir, "template.tiff");
// 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
using (RasterImage raster = (RasterImage)Image.Load(dataDir + "template.png"))
{
// Store the width & height in variables for later use
width = raster.Width;
height = raster.Height;
// 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
using (PngImage png = new PngImage(width, height, PngColorType.TruecolorWithAlpha))
{
// Save the previously loaded pixels on to the new PngImage and Set TransparentColor property to specify which color to be rendered as transparent
png.SavePixels(new Rectangle(0, 0, width, height), pixels);
png.TransparentColor = Color.Black;
png.HasTransparentColor = true;
png.Save(dataDir + "result.jpg");
}
File.Delete(dataDir + "result.jpg");

Setting Resolution for PNG Images

With Aspose.Imaging for .NET 2.5.0, the API exposes the ResolutionSetting class which can be used to set the resolution for all image formats including PNG. This article demonstrates the usage of the Aspose.Imaging for .NET API to set the horizontal & vertical resolution parameters for the PNG image format. The code snippet below loads an existing BMP image and converts it to PNG format also changing the resolution.

using Aspose.Imaging;
using Aspose.Imaging.Brushes;
using Aspose.Imaging.FileFormats.Bmp;
using Aspose.Imaging.FileFormats.Core.VectorPaths;
using Aspose.Imaging.FileFormats.Emf;
using Aspose.Imaging.FileFormats.Emf.Emf.Consts;
using Aspose.Imaging.FileFormats.Emf.Graphics;
using Aspose.Imaging.FileFormats.Gif;
using Aspose.Imaging.FileFormats.Gif.Blocks;
using Aspose.Imaging.FileFormats.Png;
using Aspose.Imaging.FileFormats.Tiff;
using Aspose.Imaging.FileFormats.Tiff.Enums;
using Aspose.Imaging.FileFormats.Tiff.PathResources;
using Aspose.Imaging.FileFormats.Webp;
using Aspose.Imaging.FileFormats.Wmf;
using Aspose.Imaging.FileFormats.Wmf.Graphics;
using Aspose.Imaging.ImageOptions;
using Aspose.Imaging.Sources;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
string templatesFolder = @"c:\Users\USER\Downloads\templates\";
string dataDir = templatesFolder;
string fileName = Path.Combine(dataDir, "template.tiff");
// 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
using (RasterImage raster = (RasterImage)Image.Load(dataDir + "template.png"))
{
// Store the width & height in variables for later use
width = raster.Width;
height = raster.Height;
// 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
using (PngImage png = new PngImage(width, height))
{
// Save the previously loaded pixels on to the new PngImage
png.SavePixels(new Rectangle(0, 0, width, height), pixels);
// Create an instance of PngOptions, Set the horizontal & vertical resolutions and Save the result on disc
PngOptions options = new PngOptions();
options.ResolutionSettings = new ResolutionSetting(72, 96);
png.Save(dataDir + "result.png", options);
}
File.Delete(dataDir + "result.png");

Compressing PNG Files

The Portable Network Graphic (PNG) is a lossless compression format for transmitting a bitmap over networks. When you save an image as a PNG file in any program, you may be asked to choose a compression level in a range from 0 to any max level. Setting this value actually compresses the file size and does not decrease the image quality. This article describes how Aspose.Imaging APIs allows you to control the PNG file size. Aspose.Imaging APIs can be used to set the Compression Levels for the PNG file format using the PngOptions class that has an int type CompressionLevel property. This property accepts a value from 0 to 9 where 9 is the maximum compression. The below provided code snippet demonstrates how to set the Compression Levels using Aspose.Imaging for .NET API.

using Aspose.Imaging;
using Aspose.Imaging.Brushes;
using Aspose.Imaging.FileFormats.Bmp;
using Aspose.Imaging.FileFormats.Core.VectorPaths;
using Aspose.Imaging.FileFormats.Emf;
using Aspose.Imaging.FileFormats.Emf.Emf.Consts;
using Aspose.Imaging.FileFormats.Emf.Graphics;
using Aspose.Imaging.FileFormats.Gif;
using Aspose.Imaging.FileFormats.Gif.Blocks;
using Aspose.Imaging.FileFormats.Png;
using Aspose.Imaging.FileFormats.Tiff;
using Aspose.Imaging.FileFormats.Tiff.Enums;
using Aspose.Imaging.FileFormats.Tiff.PathResources;
using Aspose.Imaging.FileFormats.Webp;
using Aspose.Imaging.FileFormats.Wmf;
using Aspose.Imaging.FileFormats.Wmf.Graphics;
using Aspose.Imaging.ImageOptions;
using Aspose.Imaging.Sources;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
string templatesFolder = @"c:\Users\USER\Downloads\templates\";
string dataDir = templatesFolder;
string fileName = Path.Combine(dataDir, "template.tiff");
// Load an image from file (or stream)
using (Image image = Image.Load(dataDir + "template.png"))
{
// Loop over possible CompressionLevel range
for (int i = 0; i <= 9; i++)
{
// Create an instance of PngOptions for each resultant PNG, Set CompressionLevel and Save result on disk
PngOptions options = new PngOptions();
options.CompressionLevel = i;
image.Save(dataDir + i + "_out.png", options);
File.Delete(dataDir + i + "_out.png");
}
}

Specifying Bit Depth for PNG Images

Bit depth in imaging is the number of bits used to indicate the color of a single pixel in a bitmap image. Like all other bitmap formats, PNG color depth is also represented in bit such as 1-bit (2 colors), 2-bit (4 colors), 4-bit (16 colors) and 8-bit (256 colors). Aspose.Imaging for .NET API can be used to set bit depth for PNG images using BitDepth property exposed by the PngOptions class. At the moment, the BitDepth property can be set to 1, 2, 4 or 8 bits for grayscale and indexed color types. For all other color types only 8 bits are supported. The below provided code snippet demonstrates how to set the Bit Depth of an existing PNG.

using Aspose.Imaging;
using Aspose.Imaging.Brushes;
using Aspose.Imaging.FileFormats.Bmp;
using Aspose.Imaging.FileFormats.Core.VectorPaths;
using Aspose.Imaging.FileFormats.Emf;
using Aspose.Imaging.FileFormats.Emf.Emf.Consts;
using Aspose.Imaging.FileFormats.Emf.Graphics;
using Aspose.Imaging.FileFormats.Gif;
using Aspose.Imaging.FileFormats.Gif.Blocks;
using Aspose.Imaging.FileFormats.Png;
using Aspose.Imaging.FileFormats.Tiff;
using Aspose.Imaging.FileFormats.Tiff.Enums;
using Aspose.Imaging.FileFormats.Tiff.PathResources;
using Aspose.Imaging.FileFormats.Webp;
using Aspose.Imaging.FileFormats.Wmf;
using Aspose.Imaging.FileFormats.Wmf.Graphics;
using Aspose.Imaging.ImageOptions;
using Aspose.Imaging.Sources;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
string templatesFolder = @"c:\Users\USER\Downloads\templates\";
string dataDir = templatesFolder;
string fileName = Path.Combine(dataDir, "template.tiff");
// Load an existing PNG image
using (PngImage png = (PngImage)Image.Load(dataDir + "template.png"))
{
// Create an instance of PngOptions, Set the desired ColorType, BitDepth according to the specified ColorType and save image
PngOptions options = new PngOptions();
options.ColorType = PngColorType.Grayscale;
options.BitDepth = 1;
png.Save(dataDir + "result.png", options);
}
File.Delete(dataDir + "result.png");

Applying Filter Methods on PNG Images

Aspose.Imaging for .NET provides the functionality to apply filter methods (algorithms) before compression as demonstrated in the below section. The purpose of these filter methods is to prepare the image data for optimum compression. Aspose.Imaging for .NET API can be used to apply filter methods before compressing any PNG image. For this purposes, the Aspose.Imaging for .NET API has exposed a property named FilterType of PngOptions class. It accepts PngFilterType enumeration that can be used to specify the filter method (algorithm) among the five including 0 for none. The below provided code snippet demonstrates how to apply filter method on PNG image.

using Aspose.Imaging;
using Aspose.Imaging.FileFormats.Png;
using Aspose.Imaging.ImageOptions;
using System.IO;
string templatesFolder = @"c:\Users\USER\Downloads\templates\";
string dataDir = templatesFolder;
using (PngImage png = (PngImage)Image.Load(dataDir + "template.png"))
{
// Create an instance of PngOptions, Set the PNG filter method and Save changes to the disc
PngOptions options = new PngOptions();
options.FilterType = PngFilterType.Paeth;
png.Save(dataDir + "result.png", options);
}
File.Delete(dataDir + "result.png");

Keep transparency, when indexing Png images

Aspose.Imaging for .NET supports keeping transparency for indexed png images on save. The following example shows how to save indexed png image and keep transparency.

using Aspose.Imaging;
using Aspose.Imaging.Brushes;
using Aspose.Imaging.FileFormats.Bmp;
using Aspose.Imaging.FileFormats.Core.VectorPaths;
using Aspose.Imaging.FileFormats.Emf;
using Aspose.Imaging.FileFormats.Emf.Emf.Consts;
using Aspose.Imaging.FileFormats.Emf.Graphics;
using Aspose.Imaging.FileFormats.Gif;
using Aspose.Imaging.FileFormats.Gif.Blocks;
using Aspose.Imaging.FileFormats.Png;
using Aspose.Imaging.FileFormats.Tiff;
using Aspose.Imaging.FileFormats.Tiff.Enums;
using Aspose.Imaging.FileFormats.Tiff.PathResources;
using Aspose.Imaging.FileFormats.Webp;
using Aspose.Imaging.FileFormats.Wmf;
using Aspose.Imaging.FileFormats.Wmf.Graphics;
using Aspose.Imaging.ImageOptions;
using Aspose.Imaging.Sources;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
string templatesFolder = @"c:\Users\USER\Downloads\templates\";
string dataDir = templatesFolder;
string fileName = Path.Combine(dataDir, "template.tiff");
using (RasterImage image = (RasterImage)Image.Load(dataDir + "template.png"))
{
PngOptions options = new PngOptions()
{
CompressionLevel = 9,
ColorType = PngColorType.IndexedColor,
Palette = ColorPaletteHelper.GetCloseTransparentImagePalette(image, 256),
FilterType = PngFilterType.Avg,
};
image.Save(dataDir + "result.png", options);
}
File.Delete(dataDir + "result.png");

Changing Background Color of a Transparent PNG Image

PNG format images can have transparent background. Aspose.Imaging for .NET provides the feature to change the background color of a PNG image that has transparent background. Aspose.Imaging for .NET API can be used to set/change color of a transparent PNG image. The below provided code snippet demonstrates how to set/change the background color of a transparent PNG image.

using Aspose.Imaging;
using Aspose.Imaging.FileFormats.Png;
using Aspose.Imaging.ImageOptions;
using System.IO;
string templatesFolder = @"c:\Users\USER\Downloads\templates\";
string dataDir = templatesFolder;
// Create an instance of Image class and load a PNG image
using (Image img = Image.Load(dataDir + "template.png"))
{
// Create an instance of RasterImage and get the pixels array by calling method LoadArgb32Pixels.
RasterImage rasterImg = img as RasterImage;
if (rasterImg != null)
{
int[] pixels = rasterImg.LoadArgb32Pixels(img.Bounds);
if (pixels != null)
{
// Iterate through the pixel array and Check the pixel information that if it is a transparent color pixel and Change the pixel color to white
for (int i = 0; i < pixels.Length; i++)
{
if (pixels[i] == rasterImg.TransparentColor.ToArgb())
{
pixels[i] = Color.White.ToArgb();
}
}
// Replace the pixel array into the image.
rasterImg.SaveArgb32Pixels(img.Bounds, pixels);
}
}
// Save the updated image to disk.
if (rasterImg != null)
rasterImg.Save(dataDir + "result.png");
}
File.Delete(dataDir + "result.png");

Optimizing Memory Usage

When reading a big PNG file, the total amount of RAM the process will take is always a concern. There are measures which can be adopted to cope with the challenge. Aspose.Imaging provides some relevant options and API calls to lower, reduce and optimize memory use. Also, it can help the process work more efficiently and run faster.

The following example shows how to read a large PNG file in optimized mode.

using Aspose.Imaging;
using Aspose.Imaging.FileFormats.Png;
using Aspose.Imaging.ImageOptions;
using System.IO;
string templatesFolder = @"c:\Users\USER\Downloads\templates\";
string dataDir = templatesFolder;
// Enabling the global memory usage optimization strategy.
// Setting a global memory limit of 50 megabytes
Aspose.Imaging.MemoryManagement.Configuration.BufferSizeHint = 50;
using (var image = Image.Load(dataDir + "template.png"))
{
image.Save(dataDir + "result.jpg", new Aspose.Imaging.ImageOptions.JpegOptions());
}
File.Delete(dataDir + "result.jpg");