Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Aspose.PSD for .NET
Gist for Aspose.PSD for .NET.
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"gauss_wiener_out.gif";
// Load the noisy image
using (Image image = Image.Load(sourceFile))
{
RasterImage rasterImage = image as RasterImage;
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.Grayscale = true;
// Apply MedianFilterOptions filter to RasterImage object and Save the resultant image
rasterImage.Filter(image.Bounds, options);
image.Save(destName, new GifOptions());
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"gauss_wiener_color_out.gif";
// Load the noisy image
using (Image image = Image.Load(sourceFile))
{
// Cast the image into RasterImage
RasterImage rasterImage = image as RasterImage;
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.Brightness = 1;
// Apply MedianFilterOptions filter to RasterImage object and Save the resultant image
rasterImage.Filter(image.Bounds, options);
image.Save(destName, new GifOptions());
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"median_test_denoise_out.gif";
// Load the noisy image
using (Image image = Image.Load(sourceFile))
{
// Cast the image into RasterImage
RasterImage rasterImage = image as RasterImage;
if (rasterImage == null)
{
return;
}
// Create an instance of MedianFilterOptions class and set the size, Apply MedianFilterOptions filter to RasterImage object and Save the resultant image
MedianFilterOptions options = new MedianFilterOptions(4);
rasterImage.Filter(image.Bounds, options);
image.Save(destName, new GifOptions());
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"motion_filter_out.gif";
// Load the noisy image
using (Image image = Image.Load(sourceFile))
{
// Cast the image into RasterImage
RasterImage rasterImage = image as RasterImage;
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.Grayscale = true;
// Apply MedianFilterOptions filter to RasterImage object and Save the resultant image
rasterImage.Filter(image.Bounds, options);
image.Save(destName, new GifOptions());
}
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());
}
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());
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"binarized_out.png";
// Load the noisy image
// Load an image
using (PsdImage image = (PsdImage)Image.Load(sourceFile))
{
// Define threshold value, Call BinarizeBradley method and pass the threshold value as parameter and Save the output image
double threshold = 0.15;
image.BinarizeBradley(threshold);
image.Save(destName, new PngOptions());
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"output.tiff";
using (Image image = Image.Load(sourceFile))
{
image.Save(destName, new TiffOptions(TiffExpectedFormat.TiffLzwCmyk));
}
// Create a new Image.
using (PsdImage image = new PsdImage(500, 500))
{
// Fill image data.
int count = image.Width * image.Height;
int[] pixels = new int[count];
int r = 0;
int g = 0;
int b = 0;
int channel = 0;
for (int i = 0; i < count; i++)
{
if (channel % 3 == 0)
{
r++;
if (r == 256)
{
r = 0;
channel++;
}
}
else if (channel % 3 == 1)
{
g++;
if (g == 256)
{
g = 0;
channel++;
}
}
else
{
b++;
if (b == 256)
{
b = 0;
channel++;
}
}
pixels[i] = Color.FromArgb(r, g, b).ToArgb();
}
// Save the newly created pixels.
image.SaveArgb32Pixels(image.Bounds, pixels);
// Save the newly created image.
image.Save(dataDir+"Default.jpg",new JpegOptions());
// Update color profile.
StreamSource rgbprofile = new StreamSource(File.OpenRead(dataDir + "eciRGB_v2.icc"));
StreamSource cmykprofile = new StreamSource(File.OpenRead(dataDir + "ISOcoated_v2_FullGamut4.icc"));
image.RgbColorProfile = rgbprofile;
image.CmykColorProfile = cmykprofile;
// Save the resultant image with new YCCK profiles. You will notice differences in color values if compare the images.
JpegOptions options = new JpegOptions();
options.ColorType = JpegCompressionColorMode.Cmyk;
image.Save(dataDir + "Cmyk_Default_profiles.jpg", options);
}
// Create a new Image.
using (PsdImage image = new PsdImage(500, 500))
{
// Fill image data.
int count = image.Width * image.Height;
int[] pixels = new int[count];
int r = 0;
int g = 0;
int b = 0;
int channel = 0;
for (int i = 0; i < count; i++)
{
if (channel % 3 == 0)
{
r++;
if (r == 256)
{
r = 0;
channel++;
}
}
else if (channel % 3 == 1)
{
g++;
if (g == 256)
{
g = 0;
channel++;
}
}
else
{
b++;
if (b == 256)
{
b = 0;
channel++;
}
}
pixels[i] = Color.FromArgb(r, g, b).ToArgb();
}
// Save the newly created pixels.
image.SaveArgb32Pixels(image.Bounds, pixels);
// Save the resultant image with default Icc profiles.
image.Save(dataDir+"Default_profiles.jpg",new JpegOptions());
// Update color profile.
StreamSource rgbprofile = new StreamSource(File.OpenRead(dataDir+"eciRGB_v2.icc"));
StreamSource cmykprofile = new StreamSource(File.OpenRead(dataDir + "ISOcoated_v2_FullGamut4.icc"));
image.RgbColorProfile = rgbprofile;
image.CmykColorProfile = cmykprofile;
// Save the resultant image with new YCCK profiles. You will notice differences in color values if compare the images.
JpegOptions options = new JpegOptions();
options.ColorType = JpegCompressionColorMode.Ycck;
image.Save(dataDir + "Ycck_profiles.jpg", options);
}
String srcPath = dataDir + @"sample.psd";
string destName = dataDir + @"export.png";
// Load an existing PSD image
using (RasterImage image = (RasterImage)Image.Load(srcPath))
{
// Create an instance of Rectangle class by passing x,y and width,height
// Call the crop method of Image class and pass the rectangle class instance
image.Crop(new Rectangle(0, 0, 350, 450));
// Create an instance of PngOptions class
PngOptions pngOptions = new PngOptions();
// Call the save method, provide output path and PngOptions to convert the PSD file to PNG and save the output
image.Save(destName, pngOptions);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
// Implement correct Crop method for PSD files.
string sourceFileName = dataDir + "1.psd";
string exportPathPsd = dataDir +"CropTest.psd";
string exportPathPng = dataDir +"CropTest.png";
using (RasterImage image = Image.Load(sourceFileName) as RasterImage)
{
image.Crop(new Rectangle(10, 30, 100, 100));
image.Save(exportPathPsd, new PsdOptions());
image.Save(exportPathPng, new PngOptions() { ColorType = PngColorType.TruecolorWithAlpha });
}
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);
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"Grayscaling_out.jpg";
// Load an image in an instance of 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();
}
// Transform image to its grayscale representation and Save the resultant image
rasterCachedImage.Grayscale();
rasterCachedImage.Save(destName, new JpegOptions());
}
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);
}
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + "result.png";
FileStream fStream = new FileStream(sourceFile, FileMode.Open);
fStream.Position = 0;
// load PSD image and replace the non found fonts.
using (Image image = Image.Load(fStream))
{
PsdImage psdImage = (PsdImage)image;
MemoryStream stream = new MemoryStream();
psdImage.Save(stream, new PngOptions());
}
String srcPath = dataDir + @"sample.psd";
string destName = dataDir+ @"export";
// Load an existing PSD image as Image
using (Image image = Image.Load(srcPath))
{
// Create an instance of PngOptions class
PngOptions pngOptions = new PngOptions();
// Create an instance of BmpOptions class
BmpOptions bmpOptions = new BmpOptions();
// Create an instance of TiffOptions class
TiffOptions tiffOptions = new TiffOptions(FileFormats.Tiff.Enums.TiffExpectedFormat.Default);
// Create an instance of GifOptions class
GifOptions gifOptions = new GifOptions();
// Create an instance of JpegOptions class
JpegOptions jpegOptions = new JpegOptions();
// Create an instance of Jpeg2000Options class
Jpeg2000Options jpeg2000Options = new Jpeg2000Options();
// Call the save method, provide output path and export options to convert PSD file to various raster file formats.
image.Save(destName + ".png", pngOptions);
image.Save(destName + ".bmp", bmpOptions);
image.Save(destName + ".tiff", tiffOptions);
image.Save(destName + ".gif", gifOptions);
image.Save(destName + ".jpeg", jpegOptions);
image.Save(destName + ".jp2", jpeg2000Options);
}
class SaveImageWorker
{
/// <summary>
/// The path to the input image.
/// </summary>
private readonly string inputPath;
/// <summary>
/// The path to the output image.
/// </summary>
private readonly string outputPath;
/// <summary>
/// The interrupt monitor.
/// </summary>
private readonly InterruptMonitor monitor;
/// <summary>
/// The save options.
/// </summary>
private readonly ImageOptionsBase saveOptions;
/// <summary>
/// Initializes a new instance of the <see cref="SaveImageWorker" /> class.
/// </summary>
/// <param name="inputPath">The path to the input image.</param>
/// <param name="outputPath">The path to the output image.</param>
/// <param name="saveOptions">The save options.</param>
/// <param name="monitor">The interrupt monitor.</param>
public SaveImageWorker(string inputPath, string outputPath, ImageOptionsBase saveOptions, InterruptMonitor monitor)
{
this.inputPath = inputPath;
this.outputPath = outputPath;
this.saveOptions = saveOptions;
this.monitor = monitor;
}
/// <summary>
/// Tries to convert image from one format to another. Handles interruption.
/// </summary>
public void ThreadProc()
{
using (Image image = Image.Load(this.inputPath))
{
InterruptMonitor.ThreadLocalInstance = this.monitor;
try
{
image.Save(this.outputPath, this.saveOptions);
}
catch (OperationInterruptedException e)
{
Console.WriteLine("The save thread #{0} finishes at {1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now);
Console.WriteLine(e);
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
InterruptMonitor.ThreadLocalInstance = null;
}
}
}
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + "result.png";
// load PSD image and replace the non found fonts.
using (Image image = Image.Load(sourceFile))
{
PsdImage psdImage = (PsdImage)image;
psdImage.Save(destName, new PngOptions());
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + "result.png";
// load PSD image and replace the non found fonts.
using (Image image = Image.Load(sourceFile))
{
PsdImage psdImage = (PsdImage)image;
MemoryStream stream = new MemoryStream();
psdImage.Save(stream, new PngOptions());
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + "result.png";
// load PSD image and replace the non found fonts.
using (Image image = Image.Load(sourceFile, new PsdLoadOptions() { DefaultReplacementFont = "Arial" }))
{
PsdImage psdImage = (PsdImage)image;
psdImage.Save(destName, new PngOptions() { ColorType = PngColorType.TruecolorWithAlpha });
}
string dataDir = RunExamples.GetDataDir_PNG();
ImageOptionsBase saveOptions = new PngOptions();
InterruptMonitor monitor = new InterruptMonitor();
string source = Path.Combine(dataDir, "big2.psb");
string output = Path.Combine(dataDir, "big_out.png");
SaveImageWorker worker = new SaveImageWorker(source, output, saveOptions, monitor);
Thread thread = new Thread(new ThreadStart(worker.ThreadProc));
try
{
thread.Start();
// The timeout should be less than the time required for full image conversion (without interruption).
Thread.Sleep(3000);
// Interrupt the process
monitor.Interrupt();
Console.WriteLine("Interrupting the save thread #{0} at {1}", thread.ManagedThreadId, System.DateTime.Now);
// Wait for interruption...
thread.Join();
}
finally
{
// Delete the output file.
if (File.Exists(output))
{
File.Delete(output);
}
}
// 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
}
}
}
// Add color overlay layer effect at runtime
string dataDir = RunExamples.GetDataDir_PSD();
string sourceFileName =dataDir+"ThreeRegularLayers.psd";
string exportPath = dataDir+"ThreeRegularLayersChanged.psd";
var loadOptions = new PsdLoadOptions()
{
LoadEffectsResource = true
};
using (var im = (PsdImage)Image.Load(sourceFileName, loadOptions))
{
var effect = im.Layers[1].BlendingOptions.AddColorOverlay();
effect.Color = Color.Green;
effect.Opacity = 128;
effect.BlendMode = BlendMode.Normal;
im.Save(exportPath);
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
string sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"AdjustBrightness_out.tiff";
using (var image = (PsdImage)Image.Load(sourceFile))
{
RasterCachedImage rasterImage = image;
// Set the brightness value. The accepted values of brightness are in the range [-255, 255].
rasterImage.AdjustBrightness(-50);
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.Default);
rasterImage.Save(destName,tiffOptions);
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"AdjustContrast_out.tiff";
// Load an existing image into an instance of RasterImage class
using (var image = Image.Load(sourceFile))
{
// Cast object of Image to RasterImage
RasterImage rasterImage = (RasterImage)image;
// Check if RasterImage is cached and Cache RasterImage for better performance
if (!rasterImage.IsCached)
{
rasterImage.CacheData();
}
// Adjust the contrast
rasterImage.AdjustContrast(50);
// Create an instance of TiffOptions for the resultant image, Set various properties for the object of TiffOptions and Save the resultant image to TIFF format
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.Default);
tiffOptions.BitsPerSample = new ushort[] { 8, 8, 8 };
tiffOptions.Photometric = TiffPhotometrics.Rgb;
rasterImage.Save(destName, tiffOptions);
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"AdjustGamma_out.tiff";
// Load an existing image into an instance of RasterImage class
using (var image = Image.Load(sourceFile))
{
// Cast object of Image to RasterImage
RasterImage rasterImage = (RasterImage)image;
// Check if RasterImage is cached and Cache RasterImage for better performance
if (!rasterImage.IsCached)
{
rasterImage.CacheData();
}
// Adjust the gamma
rasterImage.AdjustGamma(2.2f, 2.2f, 2.2f);
// Create an instance of TiffOptions for the resultant image, Set various properties for the object of TiffOptions and Save the resultant image to TIFF format
TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.Default);
tiffOptions.BitsPerSample = new ushort[] { 8, 8, 8 };
tiffOptions.Photometric = TiffPhotometrics.Rgb;
rasterImage.Save(destName, tiffOptions);
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"BlurAnImage_out.gif";
// Load an existing image into an instance of RasterImage class
using (var image = Image.Load(sourceFile))
{
// Convert the image into RasterImage,
//Pass Bounds[rectangle] of image and GaussianBlurFilterOptions instance to Filter method and Save the results
RasterImage rasterImage = (RasterImage)image;
rasterImage.Filter(rasterImage.Bounds, new GaussianBlurFilterOptions(15, 15));
rasterImage.Save(destName, new GifOptions());
}
// ColorOverlay effect editing
string sourceFileName = dataDir+"ColorOverlay.psd";
string psdPathAfterChange =dataDir+ "ColorOverlayChanged.psd";
var loadOptions = new PsdLoadOptions()
{
LoadEffectsResource = true
};
using (var im = (PsdImage)Image.Load(sourceFileName, loadOptions))
{
var colorOverlay = (ColorOverlayEffect)(im.Layers[1].BlendingOptions.Effects[0]);
Assert.AreEqual(Color.Red, colorOverlay.Color);
Assert.AreEqual(153, colorOverlay.Opacity);
colorOverlay.Color = Color.Green;
colorOverlay.Opacity = 128;
im.Save(psdPathAfterChange);
}
// 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();
}
// 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 ...
}
}
}
}
string desName = dataDir + "CreatingAnImageBySettingPath_out.psd";
// Creates an instance of PsdOptions and set its various properties
PsdOptions psdOptions = new PsdOptions();
psdOptions.CompressionMethod = CompressionMethod.RLE;
// Define the source property for the instance of PsdOptions. Second boolean parameter determines if the file is temporal or not
psdOptions.Source = new FileCreateSource(desName, false);
// Creates an instance of Image and call Create method by passing the PsdOptions object
using (Image image = Image.Create(psdOptions, 500, 500))
{
image.Save();
}
string desName = dataDir + "CreatingImageUsingStream_out.bmp";
// Creates an instance of BmpOptions and set its various properties
BmpOptions ImageOptions = new BmpOptions();
ImageOptions.BitsPerPixel = 24;
// Create an instance of System.IO.Stream
Stream stream = new FileStream(dataDir + "sample_out.bmp", FileMode.Create);
// Define the source property for the instance of BmpOptions Second boolean parameter determines if the Stream is disposed once get out of scope
ImageOptions.Source = new StreamSource(stream, true);
// Creates an instance of Image and call Create method by passing the BmpOptions object
using (Image image = Image.Create(ImageOptions, 500, 500))
{
// Do some image processing
image.Save(desName);
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"CroppingByRectangle_out.jpg";
// Load an existing image into an instance of RasterImage class
using (RasterImage rasterImage = (RasterImage)Image.Load(sourceFile))
{
if (!rasterImage.IsCached)
{
rasterImage.CacheData();
}
// Create an instance of Rectangle class with desired size,
//Perform the crop operation on object of Rectangle class and Save the results to disk
Rectangle rectangle = new Rectangle(20, 20, 20, 20);
rasterImage.Crop(rectangle);
rasterImage.Save(destName, new JpegOptions());
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"CroppingByShifts_out.jpg";
// Load an existing image into an instance of RasterImage class
using (RasterImage rasterImage = (RasterImage)Image.Load(sourceFile))
{
// Before cropping, the image should be cached for better performance
if (!rasterImage.IsCached)
{
rasterImage.CacheData();
}
// Define shift values for all four sides
int leftShift = 10;
int rightShift = 10;
int topShift = 10;
int bottomShift = 10;
// Based on the shift values, apply the cropping on image Crop method will shift the image bounds toward the center of image and Save the results to disk
rasterImage.Crop(leftShift, rightShift, topShift, bottomShift);
rasterImage.Save(destName, new JpegOptions());
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"SampleImage_out.bmp";
// Load an existing image into an instance of RasterImage class
using (var image = (PsdImage)Image.Load(sourceFile))
{
// Peform Floyd Steinberg dithering on the current image and Save the resultant image
image.Dither(DitheringMethod.ThresholdDithering, 4);
image.Save(destName, new BmpOptions());
}
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);
}
// The path to the documents directory.
// Load an image in an instance of image and setting default replacement font.
PsdLoadOptions psdLoadOptions = new PsdLoadOptions() { DefaultReplacementFont = "Arial" };
using (PsdImage psdImage = (PsdImage)Image.Load(dataDir +"Cloud_AzPlat_Banner3A_SB_EN_US_160x600_chinese_font.psd", psdLoadOptions))
{
var pngOptions = new PngOptions();
psdImage.Save(dataDir + "replaced_font.png", new ImageOptions.PngOptions());
}
// The path to the documents directory.
using (PsdImage image = (PsdImage)Image.Load(dataDir+"sample.psd"))
{
image.Save("NoFont.psd");
}
Console.WriteLine("You have 2 minutes to install the font");
Thread.Sleep(TimeSpan.FromMinutes(2));
OpenTypeFontsCache.UpdateCache();
using (PsdImage image = (PsdImage)Image.Load(dataDir+ @"sample.psd"))
{
image.Save(dataDir+"HasFont.psd");
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"anim_lossy-200.gif";
GifOptions gifExport = new GifOptions();
// Load an existing image into an instance of RasterImage class
using (var image = Image.Load(sourceFile))
{
gifExport.MaxDiff = 80;
image.Save("anim_lossy-80.gif", gifExport);
gifExport.MaxDiff = 200;
image.Save(destName, gifExport);
}
string dataDir = RunExamples.GetDataDir_PSD();
string sourceFileName = dataDir+"ColorOverlay.psd";
string pngExportPath = dataDir+"ColorOverlayresult.png";
var loadOptions = new PsdLoadOptions()
{
LoadEffectsResource = true
};
using (var im = (PsdImage)Image.Load(sourceFileName, loadOptions))
//using (var im = (PsdImage)Image.Load(sourceFileName))
{
var colorOverlay = (ColorOverlayEffect)(im.Layers[1].BlendingOptions.Effects[0]);
Assert.AreEqual(Color.Red, colorOverlay.Color);
Assert.AreEqual(153, colorOverlay.Opacity);
// Save PNG
var saveOptions = new PngOptions();
saveOptions.ColorType = PngColorType.TruecolorWithAlpha;
im.Save(pngExportPath, saveOptions);
}
}
string dataDir = RunExamples.GetDataDir_PSD();
string sourceFileName = dataDir+ "Shadow.psd";
string pngExportPath = dataDir+"Shadowchanged1.png";
var loadOptions = new PsdLoadOptions()
{
LoadEffectsResource = true
};
using (var im = (PsdImage)Image.Load(sourceFileName, loadOptions))
{
var shadowEffect = (DropShadowEffect)(im.Layers[1].BlendingOptions.Effects[0]);
Assert.AreEqual(Color.Black, shadowEffect.Color);
Assert.AreEqual(255, shadowEffect.Opacity);
Assert.AreEqual(3, shadowEffect.Distance);
Assert.AreEqual(7, shadowEffect.Size);
Assert.AreEqual(true, shadowEffect.UseGlobalLight);
Assert.AreEqual(90, shadowEffect.Angle);
Assert.AreEqual(0, shadowEffect.Spread);
Assert.AreEqual(0, shadowEffect.Noise);
// Save PNG
var saveOptions = new PngOptions();
saveOptions.ColorType = PngColorType.TruecolorWithAlpha;
im.Save(pngExportPath, saveOptions);
}
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"SimpleResizeImageProportionally_out.png";
// Load an existing image into an instance of RasterImage class
using (Image image = Image.Load(sourceFile))
{
if (!image.IsCached)
{
image.CacheData();
}
// Specifying width and height
int newWidth = image.Width / 2;
image.ResizeWidthProportionally(newWidth);
int newHeight = image.Height / 2;
image.ResizeHeightProportionally(newHeight);
image.Save(destName, new PngOptions());
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"ResizingwithResizeTypeEnumeration_out.jpg";
// Load an existing image into an instance of RasterImage class
using (Image image = Image.Load(sourceFile))
{
image.Resize(300, 300, ResizeType.LanczosResample);
image.Save(destName, new JpegOptions());
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"RotatingAnImage_out.jpg";
// Load an existing image into an instance of RasterImage class
using (Image image = Image.Load(sourceFile))
{
image.RotateFlip(RotateFlipType.Rotate270FlipNone);
image.Save(destName, new JpegOptions());
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"RotatingImageOnSpecificAngle_out.jpg";
// Load an image to be rotated in an instance of RasterImage
using (RasterImage image = (RasterImage)Image.Load(sourceFile))
{
// 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 proportional with red background color and Save the result to a new file
image.Rotate(20f, true, Color.Red);
image.Save(destName, new JpegOptions());
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"SimpleResizing_out.jpg";
// Load an existing image into an instance of RasterImage class
using (Image image = Image.Load(sourceFile))
{
image.Resize(300, 300);
image.Save(destName, new JpegOptions());
}
var files = new string[]
{
"Normal",
"Dissolve",
"Darken",
"Multiply",
"ColorBurn",
"LinearBurn",
"DarkerColor",
"Lighten",
"Screen",
"ColorDodge",
"LinearDodgeAdd",
"LightenColor",
"Overlay",
"SoftLight",
"HardLight",
"VividLight",
"LinearLight",
"PinLight",
"HardMix",
"Difference",
"Exclusion",
"Subtract",
"Divide",
"Hue",
"Saturation",
"Color",
"Luminosity",
};
foreach (var fileName in files)
{
using (var im = (PsdImage)Image.Load(fileName + ".psd"))
{
// Export to PNG
var saveOptions = new PngOptions();
saveOptions.ColorType = PngColorType.TruecolorWithAlpha;
var pngExportPath100 = "BlendMode" + fileName + "_Test100.png";
im.Save(pngExportPath100, saveOptions);
// Set opacity 50%
im.Layers[1].Opacity = 127;
var pngExportPath50 = "BlendMode" + fileName + "_Test50.png";
im.Save(pngExportPath50, saveOptions);
}
}
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_PSD();
string sourceFileName = dataDir+"Shadow.psd";
string psdPathAfterChange = dataDir+"ShadowChanged.psd";
var loadOptions = new PsdLoadOptions()
{
LoadEffectsResource = true
};
using (var im = (PsdImage)Image.Load(sourceFileName, loadOptions))
//using (var im = (PsdImage)Image.Load(sourceFileName))
{
var shadowEffect = (DropShadowEffect)(im.Layers[1].BlendingOptions.Effects[0]);
Assert.AreEqual(Color.Black, shadowEffect.Color);
Assert.AreEqual(255, shadowEffect.Opacity);
Assert.AreEqual(3, shadowEffect.Distance);
Assert.AreEqual(7, shadowEffect.Size);
Assert.AreEqual(true, shadowEffect.UseGlobalLight);
Assert.AreEqual(90, shadowEffect.Angle);
Assert.AreEqual(0, shadowEffect.Spread);
Assert.AreEqual(0, shadowEffect.Noise);
shadowEffect.Color = Color.Green;
shadowEffect.Opacity = 128;
shadowEffect.Distance = 11;
shadowEffect.UseGlobalLight = false;
shadowEffect.Size = 9;
shadowEffect.Angle = 45;
shadowEffect.Spread = 3;
shadowEffect.Noise = 50;
im.Save(psdPathAfterChange);
}
}
String sourceFile = dataDir + @"sample.psd";
string destName = dataDir + @"AdjustBrightness_out.tiff";
// Load an existing image into an instance of RasterImage class
using (PsdImage image = (PsdImage)Image.Load(sourceFile))
{
float opacity = image.ImageOpacity;
Console.WriteLine(opacity);
if (opacity == 0)
{
// The image is fully transparent.
}
}
// Gradient overlay effect. Example
string sourceFileName = dataDir + "GradientOverlay.psd";
string exportPath = dataDir + "GradientOverlayChanged.psd";
var loadOptions = new PsdLoadOptions()
{
LoadEffectsResource = true
};
using (var im = (PsdImage)Image.Load(sourceFileName, loadOptions))
{
var gradientOverlay = (GradientOverlayEffect)im.Layers[1].BlendingOptions.Effects[0];
Assert.AreEqual(BlendMode.Normal, gradientOverlay.BlendMode);
Assert.AreEqual(255, gradientOverlay.Opacity);
Assert.AreEqual(true, gradientOverlay.IsVisible);
var settings = gradientOverlay.Settings;
Assert.AreEqual(Color.Empty, settings.Color);
Assert.AreEqual(FillType.Gradient, settings.FillType);
Assert.AreEqual(true, settings.AlignWithLayer);
Assert.AreEqual(GradientType.Linear, settings.GradientType);
Assert.IsTrue(Math.Abs(33 - settings.Angle) < 0.001, "Angle is incorrect");
Assert.AreEqual(false, settings.Dither);
Assert.IsTrue(Math.Abs(129 - settings.HorizontalOffset) < 0.001, "Horizontal offset is incorrect");
Assert.IsTrue(Math.Abs(156 - settings.VerticalOffset) < 0.001, "Vertical offset is incorrect");
Assert.AreEqual(false, settings.Reverse);
// Color Points
var colorPoints = settings.ColorPoints;
Assert.AreEqual(3, colorPoints.Length);
Assert.AreEqual(Color.FromArgb(9, 0, 178), colorPoints[0].Color);
Assert.AreEqual(0, colorPoints[0].Location);
Assert.AreEqual(50, colorPoints[0].MedianPointLocation);
Assert.AreEqual(Color.Red, colorPoints[1].Color);
Assert.AreEqual(2048, colorPoints[1].Location);
Assert.AreEqual(50, colorPoints[1].MedianPointLocation);
Assert.AreEqual(Color.FromArgb(255, 252, 0), colorPoints[2].Color);
Assert.AreEqual(4096, colorPoints[2].Location);
Assert.AreEqual(50, colorPoints[2].MedianPointLocation);
// Transparency points
var transparencyPoints = settings.TransparencyPoints;
Assert.AreEqual(2, transparencyPoints.Length);
Assert.AreEqual(0, transparencyPoints[0].Location);
Assert.AreEqual(50, transparencyPoints[0].MedianPointLocation);
Assert.AreEqual(100, transparencyPoints[0].Opacity);
Assert.AreEqual(4096, transparencyPoints[1].Location);
Assert.AreEqual(50, transparencyPoints[1].MedianPointLocation);
Assert.AreEqual(100, transparencyPoints[1].Opacity);
// Test editing
settings.Color = Color.Green;
gradientOverlay.Opacity = 193;
gradientOverlay.BlendMode = BlendMode.Lighten;
settings.AlignWithLayer = false;
settings.GradientType = GradientType.Radial;
settings.Angle = 45;
settings.Dither = true;
settings.HorizontalOffset = 15;
settings.VerticalOffset = 11;
settings.Reverse = true;
// Add new color point
var colorPoint = settings.AddColorPoint();
colorPoint.Color = Color.Green;
colorPoint.Location = 4096;
colorPoint.MedianPointLocation = 75;
// Change location of previous point
settings.ColorPoints[2].Location = 3000;
// Add new transparency point
var transparencyPoint = settings.AddTransparencyPoint();
transparencyPoint.Opacity = 25;
transparencyPoint.MedianPointLocation = 25;
transparencyPoint.Location = 4096;
// Change location of previous transparency point
settings.TransparencyPoints[1].Location = 2315;
im.Save(exportPath);
}
// Test file after edit
using (var im = (PsdImage)Image.Load(sourceFileName, loadOptions))
{
var gradientOverlay = (GradientOverlayEffect)im.Layers[1].BlendingOptions.Effects[0];
try
{
Assert.AreEqual(BlendMode.Lighten, gradientOverlay.BlendMode);
Assert.AreEqual(193, gradientOverlay.Opacity);
Assert.AreEqual(true, gradientOverlay.IsVisible);
var fillSettings = gradientOverlay.Settings;
Assert.AreEqual(Color.Empty, fillSettings.Color);
Assert.AreEqual(FillType.Gradient, fillSettings.FillType);
// Check color points
Assert.AreEqual(4, fillSettings.ColorPoints.Length);
var point = fillSettings.ColorPoints[0];
Assert.AreEqual(50, point.MedianPointLocation);
Assert.AreEqual(Color.FromArgb(9, 0, 178), point.Color);
Assert.AreEqual(0, point.Location);
point = fillSettings.ColorPoints[1];
Assert.AreEqual(50, point.MedianPointLocation);
Assert.AreEqual(Color.Red, point.Color);
Assert.AreEqual(2048, point.Location);
point = fillSettings.ColorPoints[2];
Assert.AreEqual(50, point.MedianPointLocation);
Assert.AreEqual(Color.FromArgb(255, 252, 0), point.Color);
Assert.AreEqual(3000, point.Location);
point = fillSettings.ColorPoints[3];
Assert.AreEqual(75, point.MedianPointLocation);
Assert.AreEqual(Color.Green, point.Color);
Assert.AreEqual(4096, point.Location);
// Check transparent points
Assert.AreEqual(3, fillSettings.TransparencyPoints.Length);
var transparencyPoint = fillSettings.TransparencyPoints[0];
Assert.AreEqual(50, transparencyPoint.MedianPointLocation);
Assert.AreEqual(100, transparencyPoint.Opacity);
Assert.AreEqual(0, transparencyPoint.Location);
transparencyPoint = fillSettings.TransparencyPoints[1];
Assert.AreEqual(50, transparencyPoint.MedianPointLocation);
Assert.AreEqual(100, transparencyPoint.Opacity);
Assert.AreEqual(2315, transparencyPoint.Location);
transparencyPoint = fillSettings.TransparencyPoints[2];
Assert.AreEqual(25, transparencyPoint.MedianPointLocation);
Assert.AreEqual(25, transparencyPoint.Opacity);
Assert.AreEqual(4096, transparencyPoint.Location);
}
catch(Exception e)
{
String ex = e.StackTrace;
}
}
// Make ability to add the newly generated regular layer to PsdImage
string sourceFileName = dataDir + "OneLayer.psd";
string exportPath = dataDir + "OneLayerEdited.psd";
string exportPathPng = dataDir + "OneLayerEdited.png";
using (var im = (PsdImage)Image.Load(sourceFileName))
{
// Preparing two int arrays
var data1 = new int[2500];
var data2 = new int[2500];
var rect1 = new Rectangle(0, 0, 50, 50);
var rect2 = new Rectangle(0, 0, 100, 25);
for (int i = 0; i < 2500; i++)
{
data1[i] = -10000000;
data2[i] = -10000000;
}
var layer1 = im.AddRegularLayer();
layer1.Left = 25;
layer1.Top = 25;
layer1.Right = 75;
layer1.Bottom = 75;
layer1.SaveArgb32Pixels(rect1, data1);
var layer2 = im.AddRegularLayer();
layer2.Left = 25;
layer2.Top = 150;
layer2.Right = 125;
layer2.Bottom = 175;
layer2.SaveArgb32Pixels(rect2, data2);
// Save psd
im.Save(exportPath, new PsdOptions());
// Save png
im.Save(exportPathPng, new PngOptions());
}
// Pattern overlay effect. Example
string sourceFileName = dataDir + "PatternOverlay.psd";
string exportPath = dataDir + "PatternOverlayChanged.psd";
var newPattern = new int[]
{
Color.Aqua.ToArgb(), Color.Red.ToArgb(), Color.Red.ToArgb(), Color.Aqua.ToArgb(),
Color.Aqua.ToArgb(), Color.White.ToArgb(), Color.White.ToArgb(), Color.Aqua.ToArgb(),
};
var newPatternBounds = new Rectangle(0, 0, 4, 2);
var guid = Guid.NewGuid();
var newPatternName = "$$$/Presets/Patterns/Pattern=Some new pattern name\0";
var loadOptions = new PsdLoadOptions()
{
LoadEffectsResource = true
};
using (var im = (PsdImage)Image.Load(sourceFileName, loadOptions))
{
var patternOverlay = (PatternOverlayEffect)im.Layers[1].BlendingOptions.Effects[0];
Assert.AreEqual(BlendMode.Normal, patternOverlay.BlendMode);
Assert.AreEqual(127, patternOverlay.Opacity);
Assert.AreEqual(true, patternOverlay.IsVisible);
var settings = patternOverlay.Settings;
Assert.AreEqual(Color.Empty, settings.Color);
Assert.AreEqual(FillType.Pattern, settings.FillType);
Assert.AreEqual("85163837-eb9e-5b43-86fb-e6d5963ea29a\0", settings.PatternId);
Assert.AreEqual("$$$/Presets/Patterns/OpticalSquares=Optical Squares\0", settings.PatternName);
Assert.AreEqual(null, settings.PointType);
Assert.AreEqual(100, settings.Scale);
Assert.AreEqual(false, settings.Linked);
Assert.IsTrue(Math.Abs(0 - settings.HorizontalOffset) < 0.001, "Horizontal offset is incorrect");
Assert.IsTrue(Math.Abs(0 - settings.VerticalOffset) < 0.001, "Vertical offset is incorrect");
// Test editing
settings.Color = Color.Green;
patternOverlay.Opacity = 193;
patternOverlay.BlendMode = BlendMode.Difference;
settings.HorizontalOffset = 15;
settings.VerticalOffset = 11;
PattResource resource;
foreach (var globalLayerResource in im.GlobalLayerResources)
{
if (globalLayerResource is PattResource)
{
resource = (PattResource)globalLayerResource;
resource.PatternId = guid.ToString();
resource.Name = newPatternName;
resource.SetPattern(newPattern, newPatternBounds);
}
}
settings.PatternName = newPatternName;
settings.PatternId = guid.ToString() + "\0";
im.Save(exportPath);
}
// Test file after edit
using (var im = (PsdImage)Image.Load(sourceFileName, loadOptions))
{
var patternOverlay = (PatternOverlayEffect)im.Layers[1].BlendingOptions.Effects[0];
try
{
Assert.AreEqual(BlendMode.Difference, patternOverlay.BlendMode);
Assert.AreEqual(193, patternOverlay.Opacity);
Assert.AreEqual(true, patternOverlay.IsVisible);
var fillSettings = patternOverlay.Settings;
Assert.AreEqual(Color.Empty, fillSettings.Color);
Assert.AreEqual(FillType.Pattern, fillSettings.FillType);
PattResource resource = null;
foreach (var globalLayerResource in im.GlobalLayerResources)
{
if (globalLayerResource is PattResource)
{
resource = (PattResource)globalLayerResource;
}
}
if (resource == null)
{
throw new Exception("PattResource not found");
}
// Check the pattern data
Assert.AreEqual(newPattern, resource.PatternData);
Assert.AreEqual(newPatternBounds, new Rectangle(0, 0, resource.Width, resource.Height));
Assert.AreEqual(guid.ToString(), resource.PatternId);
Assert.AreEqual(newPatternName, resource.Name);
}
catch (Exception e)
{
String ex = e.StackTrace;
}
}
// Create an instance of Image and load the primary image
using (Image canvas = Image.Load(dataDir + "layers.psd"))
{
// Create another instance of Image and load the secondary image containing the signature graphics
using (Image signature = Image.Load(dataDir + "sample.psd"))
{
// Create an instance of Graphics class and initialize it using the object of the primary image
Graphics graphics = new Graphics(canvas);
// Call the DrawImage method while passing the instance of secondary image and appropriate location. The following snippet tries to draw the secondary image at the right bottom of the primary image
graphics.DrawImage(signature, new Point(canvas.Height - signature.Height, canvas.Width - signature.Width));
canvas.Save(dataDir + "AddSignatureToImage_out.png", new PngOptions());
}
}
// Stroke effect. FillType - Color. Example
string sourceFileName = dataDir+ "Stroke.psd";
string exportPath = dataDir+"StrokeGradientChanged.psd";
var loadOptions = new PsdLoadOptions()
{
LoadEffectsResource = true
};
using (var im = (PsdImage)Image.Load(sourceFileName, loadOptions))
{
var colorStroke = (StrokeEffect)im.Layers[1].BlendingOptions.Effects[0];
Assert.AreEqual(BlendMode.Normal, colorStroke.BlendMode);
Assert.AreEqual(255, colorStroke.Opacity);
Assert.AreEqual(true, colorStroke.IsVisible);
var fillSettings = (ColorFillSettings)colorStroke.FillSettings;
Assert.AreEqual(Color.Black, fillSettings.Color);
Assert.AreEqual(FillType.Color, fillSettings.FillType);
fillSettings.Color = Color.Yellow;
colorStroke.Opacity = 127;
colorStroke.BlendMode = BlendMode.Color;
im.Save(exportPath);
}
// Test file after edit
using (var im = (PsdImage)Image.Load(exportPath, loadOptions))
{
var colorStroke = (StrokeEffect)im.Layers[1].BlendingOptions.Effects[0];
Assert.AreEqual(BlendMode.Color, colorStroke.BlendMode);
Assert.AreEqual(127, colorStroke.Opacity);
Assert.AreEqual(true, colorStroke.IsVisible);
var fillSettings = (ColorFillSettings)colorStroke.FillSettings;
Assert.AreEqual(Color.Yellow, fillSettings.Color);
Assert.AreEqual(FillType.Color, fillSettings.FillType);
}
// Stroke effect. FillType - Gradient. Example
string sourceFileName = dataDir+ "Stroke.psd";
string exportPath = dataDir+"StrokeGradientChanged.psd";
var loadOptions = new PsdLoadOptions()
{
LoadEffectsResource = true
};
using (var im = (PsdImage)Image.Load(sourceFileName, loadOptions))
{
var gradientStroke = (StrokeEffect)im.Layers[2].BlendingOptions.Effects[0];
Assert.AreEqual(BlendMode.Normal, gradientStroke.BlendMode);
Assert.AreEqual(255, gradientStroke.Opacity);
Assert.AreEqual(true, gradientStroke.IsVisible);
var fillSettings = (GradientFillSettings)gradientStroke.FillSettings;
Assert.AreEqual(Color.Black, fillSettings.Color);
Assert.AreEqual(FillType.Gradient, fillSettings.FillType);
Assert.AreEqual(true, fillSettings.AlignWithLayer);
Assert.AreEqual(GradientType.Linear, fillSettings.GradientType);
Assert.IsTrue(Math.Abs(90 - fillSettings.Angle) < 0.001, "Angle is incorrect");
Assert.AreEqual(false, fillSettings.Dither);
Assert.IsTrue(Math.Abs(0 - fillSettings.HorizontalOffset) < 0.001, "Horizontal offset is incorrect");
Assert.IsTrue(Math.Abs(0 - fillSettings.VerticalOffset) < 0.001, "Vertical offset is incorrect");
Assert.AreEqual(false, fillSettings.Reverse);
// Color Points
var colorPoints = fillSettings.ColorPoints;
Assert.AreEqual(2, colorPoints.Length);
Assert.AreEqual(Color.Black, colorPoints[0].Color);
Assert.AreEqual(0, colorPoints[0].Location);
Assert.AreEqual(50, colorPoints[0].MedianPointLocation);
Assert.AreEqual(Color.White, colorPoints[1].Color);
Assert.AreEqual(4096, colorPoints[1].Location);
Assert.AreEqual(50, colorPoints[1].MedianPointLocation);
// Transparency points
var transparencyPoints = fillSettings.TransparencyPoints;
Assert.AreEqual(2, transparencyPoints.Length);
Assert.AreEqual(0, transparencyPoints[0].Location);
Assert.AreEqual(50, transparencyPoints[0].MedianPointLocation);
Assert.AreEqual(100, transparencyPoints[0].Opacity);
Assert.AreEqual(4096, transparencyPoints[1].Location);
Assert.AreEqual(50, transparencyPoints[1].MedianPointLocation);
Assert.AreEqual(100, transparencyPoints[1].Opacity);
// Test editing
fillSettings.Color = Color.Green;
gradientStroke.Opacity = 127;
gradientStroke.BlendMode = BlendMode.Color;
fillSettings.AlignWithLayer = false;
fillSettings.GradientType = GradientType.Radial;
fillSettings.Angle = 45;
fillSettings.Dither = true;
fillSettings.HorizontalOffset = 15;
fillSettings.VerticalOffset = 11;
fillSettings.Reverse = true;
// Add new color point
var colorPoint = fillSettings.AddColorPoint();
colorPoint.Color = Color.Green;
colorPoint.Location = 4096;
colorPoint.MedianPointLocation = 75;
// Change location of previous point
fillSettings.ColorPoints[1].Location = 1899;
// Add new transparency point
var transparencyPoint = fillSettings.AddTransparencyPoint();
transparencyPoint.Opacity = 25;
transparencyPoint.MedianPointLocation = 25;
transparencyPoint.Location = 4096;
// Change location of previous transparency point
fillSettings.TransparencyPoints[1].Location = 2411;
im.Save(exportPath);
}
// Test file after edit
using (var im = (PsdImage)Image.Load(exportPath, loadOptions))
{
var gradientStroke = (StrokeEffect)im.Layers[2].BlendingOptions.Effects[0];
Assert.AreEqual(BlendMode.Color, gradientStroke.BlendMode);
Assert.AreEqual(127, gradientStroke.Opacity);
Assert.AreEqual(true, gradientStroke.IsVisible);
var fillSettings = (GradientFillSettings)gradientStroke.FillSettings;
Assert.AreEqual(Color.Green, fillSettings.Color);
Assert.AreEqual(FillType.Gradient, fillSettings.FillType);
// Check color points
Assert.AreEqual(3, fillSettings.ColorPoints.Length);
var point = fillSettings.ColorPoints[0];
Assert.AreEqual(50, point.MedianPointLocation);
Assert.AreEqual(Color.Black, point.Color);
Assert.AreEqual(0, point.Location);
point = fillSettings.ColorPoints[1];
Assert.AreEqual(50, point.MedianPointLocation);
Assert.AreEqual(Color.White, point.Color);
Assert.AreEqual(1899, point.Location);
point = fillSettings.ColorPoints[2];
Assert.AreEqual(75, point.MedianPointLocation);
Assert.AreEqual(Color.Green, point.Color);
Assert.AreEqual(4096, point.Location);
// Check transparent points
Assert.AreEqual(3, fillSettings.TransparencyPoints.Length);
var transparencyPoint = fillSettings.TransparencyPoints[0];
Assert.AreEqual(50, transparencyPoint.MedianPointLocation);
Assert.AreEqual(100, transparencyPoint.Opacity);
Assert.AreEqual(0, transparencyPoint.Location);
transparencyPoint = fillSettings.TransparencyPoints[1];
Assert.AreEqual(50, transparencyPoint.MedianPointLocation);
Assert.AreEqual(100, transparencyPoint.Opacity);
Assert.AreEqual(2411, transparencyPoint.Location);
transparencyPoint = fillSettings.TransparencyPoints[2];
Assert.AreEqual(25, transparencyPoint.MedianPointLocation);
Assert.AreEqual(25, transparencyPoint.Opacity);
Assert.AreEqual(4096, transparencyPoint.Location);
}
// Stroke effect. FillType - Pattern. Example
string sourceFileName = dataDir+"Stroke.psd";
string exportPath = dataDir+"StrokePatternChanged.psd";
var loadOptions = new PsdLoadOptions()
{
LoadEffectsResource = true
};
// Preparing new data
var newPattern = new int[]
{
Color.Aqua.ToArgb(), Color.Red.ToArgb(), Color.Red.ToArgb(), Color.Aqua.ToArgb(),
Color.Aqua.ToArgb(), Color.White.ToArgb(), Color.White.ToArgb(), Color.Aqua.ToArgb(),
Color.Aqua.ToArgb(), Color.White.ToArgb(), Color.White.ToArgb(), Color.Aqua.ToArgb(),
Color.Aqua.ToArgb(), Color.Red.ToArgb(), Color.Red.ToArgb(), Color.Aqua.ToArgb(),
};
var newPatternBounds = new Rectangle(0, 0, 4, 4);
var guid = Guid.NewGuid();
using (var im = (PsdImage)Image.Load(sourceFileName, loadOptions))
{
var patternStroke = (StrokeEffect)im.Layers[3].BlendingOptions.Effects[0];
Assert.AreEqual(BlendMode.Normal, patternStroke.BlendMode);
Assert.AreEqual(255, patternStroke.Opacity);
Assert.AreEqual(true, patternStroke.IsVisible);
var fillSettings = (PatternFillSettings)patternStroke.FillSettings;
Assert.AreEqual(FillType.Pattern, fillSettings.FillType);
patternStroke.Opacity = 127;
patternStroke.BlendMode = BlendMode.Color;
PattResource resource;
foreach (var globalLayerResource in im.GlobalLayerResources)
{
if (globalLayerResource is PattResource)
{
resource = (PattResource)globalLayerResource;
resource.PatternId = guid.ToString();
resource.Name = "$$$/Presets/Patterns/HorizontalLine1=Horizontal Line 9\0";
resource.SetPattern(newPattern, newPatternBounds);
}
}
((PatternFillSettings)patternStroke.FillSettings).PatternName = "$$$/Presets/Patterns/HorizontalLine1=Horizontal Line 9\0";
((PatternFillSettings)patternStroke.FillSettings).PatternId = guid.ToString() + "\0";
im.Save(exportPath);
}
// Test file after edit
using (var im = (PsdImage)Image.Load(sourceFileName, loadOptions))
{
var patternStroke = (StrokeEffect)im.Layers[3].BlendingOptions.Effects[0];
PattResource resource = null;
foreach (var globalLayerResource in im.GlobalLayerResources)
{
if (globalLayerResource is PattResource)
{
resource = (PattResource)globalLayerResource;
}
}
if (resource == null)
{
throw new Exception("PattResource not found");
}
try
{
// Check the pattern data
Assert.AreEqual(newPattern, resource.PatternData);
Assert.AreEqual(newPatternBounds, new Rectangle(0, 0, resource.Width, resource.Height));
Assert.AreEqual(guid.ToString(), resource.PatternId);
Assert.AreEqual(BlendMode.Color, patternStroke.BlendMode);
Assert.AreEqual(127, patternStroke.Opacity);
Assert.AreEqual(true, patternStroke.IsVisible);
var fillSettings = (PatternFillSettings)patternStroke.FillSettings;
Assert.AreEqual(FillType.Pattern, fillSettings.FillType);
}
catch(Exception e)
{
String ex = e.StackTrace;
}
}
// Create an instance of BmpOptions and set its various properties
string loadpath = dataDir + "sample.psd";
string outpath = dataDir + "CoreDrawingFeatures.bmp";
// Create an instance of Image
using (PsdImage image = new PsdImage(loadpath))
{
// load pixels
var pixels = image.LoadArgb32Pixels(new Rectangle(0, 0, 100, 10));
for (int i = 0; i < pixels.Length; i++)
{
// specify pixel color value (gradient in this case).
pixels[i] = i;
}
// save modified pixels.
image.SaveArgb32Pixels(new Rectangle(0, 0, 100, 10), pixels);
// export image to bmp file format.
image.Save(outpath, new BmpOptions());
}
// Create an instance of BmpOptions and set its various properties
string outpath = dataDir + "Arc.bmp";
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.BitsPerPixel = 32;
// Create an instance of Image
using (Image image = new PsdImage(100, 100))
{
// Create and initialize an instance of Graphics class and clear Graphics surface
Graphics graphic = new Graphics(image);
graphic.Clear(Color.Yellow);
// Draw an 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 and save all changes.
graphic.DrawArc(new Pen(Color.Black), 0, 0, width, height, startAngle, sweepAngle);
// export image to bmp file format.
image.Save(outpath, saveOptions);
}
// Create an instance of BmpOptions and set its various properties
string outpath = dataDir + "Bezier.bmp";
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.BitsPerPixel = 32;
// Create an instance of Image
using (Image image = new PsdImage(100, 100))
{
// Create and initialize an instance of Graphics class and clear Graphics surface
Graphics graphic = new Graphics(image);
graphic.Clear(Color.Yellow);
// Initializes the instance of PEN class with black color and width
Pen BlackPen = new Pen(Color.Black, 3);
float startX = 10;
float startY = 25;
float controlX1 = 20;
float controlY1 = 5;
float controlX2 = 55;
float controlY2 = 10;
float endX = 90;
float endY = 25;
// Draw a Bezier shape by specifying the Pen object having black color and co-ordinate Points and save all changes.
graphic.DrawBezier(BlackPen, startX, startY, controlX1, controlY1, controlX2, controlY2, endX, endY);
// export image to bmp file format.
image.Save(outpath, saveOptions);
}
// Create an instance of BmpOptions and set its various properties
string outpath = dataDir + "Ellipse.bmp";
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.BitsPerPixel = 32;
// Create an instance of Image
using (Image image = new PsdImage(100, 100))
{
// Create and initialize an instance of Graphics class and Clear Graphics surface
Graphics graphic = new Graphics(image);
graphic.Clear(Color.Yellow);
// Draw a dotted ellipse shape by specifying the Pen object having red color and a surrounding Rectangle
graphic.DrawEllipse(new Pen(Color.Red), new 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 SolidBrush(Color.Blue)), new Rectangle(10, 30, 80, 40));
// export image to bmp file format.
image.Save(outpath, saveOptions);
}
// Create an instance of BmpOptions and set its various properties
string outpath = dataDir + "Lines.bmp";
BmpOptions saveOptions = new BmpOptions();
saveOptions.BitsPerPixel = 32;
// Create an instance of Image
using (Image image = new PsdImage(100, 100))
{
// Create and initialize an instance of Graphics class and Clear Graphics surface
Graphics graphic = new Graphics(image);
graphic.Clear(Color.Yellow);
// Draw two dotted diagonal lines by specifying the Pen object having blue color and co-ordinate Points
graphic.DrawLine(new Pen(Color.Blue), 9, 9, 90, 90);
graphic.DrawLine(new Pen(Color.Blue), 9, 90, 90, 9);
// Draw a four continuous line by specifying the Pen object having Solid Brush with red color and two point structures
graphic.DrawLine(new Pen(new SolidBrush(Color.Red)), new Point(9, 9), new Point(9, 90));
graphic.DrawLine(new Pen(new SolidBrush(Color.Aqua)), new Point(9, 90), new Point(90, 90));
graphic.DrawLine(new Pen(new SolidBrush(Color.Black)), new Point(90, 90), new Point(90, 9));
graphic.DrawLine(new Pen(new SolidBrush(Color.White)), new Point(90, 9), new Point(9, 9));
image.Save(outpath, saveOptions);
}
// Create an instance of BmpOptions and set its various properties
string outpath = dataDir + "Rectangle.bmp";
// Create an instance of BmpOptions and set its various properties
BmpOptions saveOptions = new BmpOptions();
saveOptions.BitsPerPixel = 32;
// Create an instance of Image
using (Image image = new PsdImage(100, 100))
{
// Create and initialize an instance of Graphics class, Clear Graphics surface, Draw a rectangle shapes and save all changes.
Graphics graphic = new Graphics(image);
graphic.Clear(Color.Yellow);
graphic.DrawRectangle(new Pen(Color.Red), new