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.
// C# code to open a psd file, updating text layers and drawing using Graphics API in a Docker container using Aspose.PSD.
// See https://docs.aspose.com/psd/net/how-to-run-aspose-psd-in-docker/ for complete details.
using Aspose.PSD;
using Aspose.PSD.Brushes;
using Aspose.PSD.FileFormats.Png;
using Aspose.PSD.FileFormats.Psd;
using Aspose.PSD.FileFormats.Psd.Layers;
using Aspose.PSD.ImageLoadOptions;
using Aspose.PSD.ImageOptions;
namespace AsposePsdDockerSample
{
internal class Program
{
static void Main(string[] args)
{
// If you want to update text, this value shoud be true, but in this case you will need the License.
// You can get the temporary license using this article: https://purchase.aspose.com/temporary-license
// Also, if you need text editing under the linux, please add to the dockerfile the following comannds
// to install the packages:
// RUN apt-get update
// RUN yes | apt - get install - y apt - transport - https
// RUN yes | apt - get install - y libgdiplus
// RUN yes | apt - get install - y libc6 - dev
var updateText = false;
if (updateText)
{
var license = new License();
license.SetLicense(@"Aspose.PSD.NET.lic");
}
// If you want to use Blending Effects, please specify the following options:
var options = new PsdLoadOptions() { LoadEffectsResource = true };
using (var img = (PsdImage)Image.Load("PsdDockerExample.psd", options))
{
if (updateText)
{
var textLayer = (TextLayer)img.Layers[1];
textLayer.UpdateText("Welcome to the dockerized Aspose.PSD");
}
var regularLayer = img.Layers[2];
// Did you want to use Aspose.PSD in docker under the Linux? Your wish is granted, just add the second eye to Daruma
var gr = new Graphics(regularLayer);
var brush = new SolidBrush() { Color = Color.FromArgb(1, 1, 1), Opacity = 255 };
var secondEyeZone = new Rectangle(129, 77, 20, 20);
gr.FillEllipse(brush, secondEyeZone);
img.Save("Output.psd");
img.Save("Output.png", new PngOptions() { ColorType = PngColorType.TruecolorWithAlpha });
}
}
}
}
// Let's load Image with Picture Frame
using (PsdImage image = (PsdImage)Image.Load(sourceFile))
// Using Layer Display Name you can find it in the PSD Image Layers List
private Layer FindLayerByName(PsdImage image, string name)
{
var layers = image.Layers;
foreach (var layer in layers)
{
if (string.Equals(layer.DisplayName, name, StringComparison.InvariantCultureIgnoreCase))
{
return layer;
}
}
return null;
}
// Let's find layer that we want to replace
var layerToReplace = FindLayerByName(image, "LayerToReplace");
var layers = new List<Layer>(image.Layers);
using (Stream stream = new FileStream(newLayerFile, FileMode.Open))
{
var newLayer = new Layer(stream);
// Drawing of new layer on the old
var graphic = new Graphics(layerToReplace);
graphic.Clear(Color.Empty);
graphic.DrawImage(newLayer, new Rectangle(new Point(), new Size(layerToReplace.Width, layerToReplace.Height)));
}
// We also can update text layers in PSD file. This can be used for business card create automation
var layerToUpdateText = (TextLayer)FindLayerByName(image, "Place the name of the picture here");
// Simple way to update text
layerToUpdateText.UpdateText("Louis le Grand Dauphin");
// Finding layer that we want to replace
var layerToReplace = FindLayerByName(image, "LayerToReplace");
var layers = new List<Layer>(image.Layers);
var indexOfLayer = layers.IndexOf(layerToReplace);
layers.Remove(layerToReplace);
using (Stream stream = new FileStream(newLayerFile, FileMode.Open))
{
var newLayer = new Layer(stream);
// We put new layer on the same coordinate and position in Layers as the removed layer
CopyLayerPosition(layerToReplace, newLayer);
layers.Insert(indexOfLayer, newLayer);
// Save list of changed layers
image.Layers = layers.ToArray();
}
// Way to Copy Layer Coordinates in Aspose.PSD
void CopyLayerPosition(Layer from, Layer to)
{
to.Left = from.Left;
to.Top = from.Top;
to.Right = from.Right;
to.Bottom = from.Bottom;
}
void UpdateTextLayer(PsdImage image)
{
// We also can update text layers in PSD file. This can be used for business card create automation
var layerToUpdateText = (TextLayer)FindLayerByName(image, "Place the name of the picture here");
// You can create comples text layers with different styles.
var textData = layerToUpdateText.TextData;
// We will use existing style of Text Layer to create new
var textPortion = textData.Items[0];
var defaultStyle = textPortion.Style;
var defaultParagraph = textPortion.Paragraph;
ITextPortion[] newPortions = textData.ProducePortions(
new string[] { "Louis XIV\r", "of France" },
defaultStyle,
defaultParagraph);
// Updating of default styles
newPortions[0].Style.FontSize = 24;
newPortions[0].Style.FillColor = Color.RoyalBlue;
newPortions[1].Style.Leading = 20;
// Removing old text
textData.RemovePortion(0);
// Addint new text portions
foreach (var newPortion in newPortions)
{
textData.AddPortion(newPortion);
}
// Applying text update
textData.UpdateLayerData();
// Fixes of the Layer position, because new text takes 2 rows
layerToUpdateText.Top = layerToUpdateText.Top - 10;
layerToUpdateText.Bottom = layerToUpdateText.Bottom - 10;
}
LayerMaskDataFull fullMask = layer.LayerMaskData as LayerMaskDataFull;
if (fullMask != null)
{
var left = fullMask.EnclosingLeft;
var right = fullMask.EnclosingRight;
var top = fullMask.EnclosingTop;
var bottom = fullMask.EnclosingBottom;
var maskRectangle = fullMask.UserMaskRectangle;
var imageData = fullMask.UserMaskData;
var defaultColor = fullMask.BackgroundColor;
var flags = fullMask.RealFlags;
bool isDisabled = (flags & LayerMaskFlags.Disabled) != 0;
}
void AddRasterMask(LayerMaskData mask, LayerMaskDataShort newShortMask)
{
LayerMaskData mask = layer.LayerMaskData;
LayerMaskDataFull fullMask = mask as LayerMaskDataFull;
var hasRasterMask = fullMask != null ||
(mask != null && (mask.Flags & LayerMaskFlags.UserMaskFromRenderingOtherData) == 0);
if (hasRasterMask)
{
Console.WriteLine("This layer has a raster mask already, updating.");
}
if (mask != null)
{
if (fullMask != null)
{
// let's update user raster mask in a full one.
fullMask.RealFlags = newMask.Flags;
fullMask.DefaultColor = newMask.DefaultColor;
fullMask.UserMaskRectangle = newMask.MaskRectangle;
fullMask.UserMaskData = newMask.ImageData;
newMask = fullMask;
}
else if ((mask.Flags & LayerMaskFlags.UserMaskFromRenderingOtherData) != 0)
{
// let's convert the short raster mask to a full one.
fullMask = new LayerMaskDataFull();
fullMask.Flags = mask.Flags;
fullMask.MaskRectangle = mask.MaskRectangle;
fullMask.ImageData = mask.ImageData;
fullMask.RealFlags = newMask.Flags;
fullMask.DefaultColor = newMask.DefaultColor;
fullMask.UserMaskRectangle = newMask.MaskRectangle;
fullMask.UserMaskData = newMask.ImageData;
newMask = fullMask;
}
}
// Adds or updates a mask
layer.AddLayerMask(newMask);
}
LayerMaskDataShort GetRasterMask(LayerMaskData mask)
{
LayerMaskDataFull fullMask = mask as LayerMaskDataFull;
if (mask == null ||
((mask.Flags & LayerMaskFlags.UserMaskFromRenderingOtherData) != 0 && fullMask == null))
{
return null;
}
if (fullMask != null)
{
return new LayerMaskDataShort()
{
Left = fullMask.EnclosingLeft,
Right = fullMask.EnclosingRight,
Top = fullMask.EnclosingTop,
Bottom = fullMask.EnclosingBottom,
ImageData = fullMask.UserMaskData,
DefaultColor = fullMask.DefaultColor,
Flags = fullMask.RealFlags
};
}
void InvertMask(LayerMaskData mask)
{
byte[] maskBytes;
LayerMaskDataFull fullMask = mask as LayerMaskDataFull;
if (fullMask == null)
{
maskBytes = mask.ImageData;
}
else
{
maskBytes = fullMask.UserMaskData;
}
for (int i = 0; i < maskBytes.Length; i++)
{
maskBytes[i] = (byte)~maskBytes[i];
}
}
bool GetRasterMaskState(Layer layer)
{
var mask = layer.LayerMaskData;
var fullMask = mask as LayerMaskDataFull;
if (mask == null || ((mask.Flags & LayerMaskFlags.UserMaskFromRenderingOtherData) != 0 &&
fullMask == null))
{
throw new Exception("This layer has no raster mask.");
}
if (fullMask != null)
{
return (fullMask.RealFlags & LayerMaskFlags.Disabled) == 0;
}
else
{
return (mask.Flags & LayerMaskFlags.Disabled) == 0;
}
}
void SetRasterMaskState(Layer layer, bool isEnabled)
{
var mask = layer.LayerMaskData;
var fullMask = mask as LayerMaskDataFull;
if (mask == null || ((mask.Flags & LayerMaskFlags.UserMaskFromRenderingOtherData) != 0 &&
fullMask == null))
{
throw new Exception("This layer has no raster mask."));
}
if (fullMask != null)
{
if (isEnabled)
{
fullMask.RealFlags = fullMask.RealFlags & ~LayerMaskFlags.Disabled;
}
else
{
fullMask.RealFlags = fullMask.RealFlags | LayerMaskFlags.Disabled;
}
}
else
{
{
if (isEnabled)
{
mask.Flags = mask.Flags & ~LayerMaskFlags.Disabled;
}
else
{
mask.Flags = mask.Flags | LayerMaskFlags.Disabled;
}
}
}
}
LayerMaskDataShort mask = (LayerMaskDataShort)layer.LayerMaskData;
if ((mask.Flags & LayerMaskFlags.UserMaskFromRenderingOtherData) == 0)
{
var left = fullMask.Left;
var right = fullMask.Right;
var top = fullMask.Top;
var bottom = fullMask.Bottom;
var maskRectangle = mask.MaskRectangle;
var imageData = mask.ImageData;
var defaultColor = newMask.DefaultColor;
var flags = newMask.Flags;
bool isDisabled = (flags & LayerMaskFlags.Disabled) != 0;
}
bool HasLayerRasterMask(Layer layer)
{
var mask = layer.LayerMaskData;
var fullMask = mask as LayerMaskDataFull;
if (mask == null ||
((mask.Flags & LayerMaskFlags.UserMaskFromRenderingOtherData) != 0 && fullMask == null))
{
return false;
}
return true;
}
void RemoveRasterMask(Layer layer)
{
LayerMaskData mask = layer.LayerMaskData;
LayerMaskDataFull fullMask = mask as LayerMaskDataFull;
if (mask == null ||
((mask.Flags & LayerMaskFlags.UserMaskFromRenderingOtherData) != 0 && fullMask == null))
{
throw new Exception("This layer has no raster mask.");
}
if (fullMask == null)
{
layer.AddLayerMask(null);
return;
}
var vectorMask = new LayerMaskDataShort();
vectorMask.Flags = fullMask.Flags;
vectorMask.MaskRectangle = fullMask.MaskRectangle;
vectorMask.DefaultColor = fullMask.DefaultColor;
vectorMask.ImageData = fullMask.ImageData;
layer.AddLayerMask(vectorMask);
}
void UpdateRasterMask(Layer layer, Action<LayerMaskData> action)
{
var mask = layer.LayerMaskData;
var fullMask = mask as LayerMaskDataFull;
if (mask == null || ((mask.Flags & LayerMaskFlags.UserMaskFromRenderingOtherData) != 0 &&
fullMask == null))
{
throw new Exception("This layer has no raster mask.");
}
action(mask);
// Apply changes
layer.AddLayerMask(mask);
}
void UpdateVectorMask(Layer layer)
{
var vectorMask = layer.LayerMaskData;
if (vectorMask == null || (vectorMask.Flags & LayerMaskFlags.UserMaskFromRenderingOtherData) == 0)
{
throw new Exception("This layer has no vector mask.");
}
layer.AddLayerMask(vectorMask);
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
string fileName = "PathExample.psd";
using (var psdImage = (PsdImage)Image.Load(fileName))
{
// Choose a layer with vector data that you want to edit.
Layer layer = psdImage.Layers[1];
// Now we can use VectorPath instance and manipulate path data.
VectorPath vectorPath = VectorDataProvider.CreateVectorPathForLayer(layer);
// Apply changes from 'vectorPath' field to the layer.
VectorDataProvider.UpdateLayerFromVectorPath(layer, vectorPath);
}
// Accessing a figure and points.
PathShape pathShape = vectorPath.Shapes[0];
BezierKnot firstKnot = pathShape.Points[0];
// Adds new one shape
vectorPath.Shapes.Add(new PathShape());
// or gets an existing
PathShape pathShape = vectorPath.Shapes[0];
// Add new shape with points
PathShape newShape = new PathShape();
newShape.Points.Add(new BezierKnot(new PointF(65, 175), true));
newShape.Points.Add(new BezierKnot(new PointF(65, 210), true));
newShape.Points.Add(new BezierKnot(new PointF(190, 210), true));
newShape.Points.Add(new BezierKnot(new PointF(190, 175), true));
vectorPath.Shapes.Add(newShape);
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
string sourceFilePath = "form_8_2l3_7.ai";
string outputFilePath = "form_8_2l3_7_export";
void AssertIsTrue(bool condition, string message)
{
if (!condition)
{
throw new FormatException(message);
}
}
using (AiImage image = (AiImage)Image.Load(sourceFilePath))
{
AiLayerSection layer0 = image.Layers[0];
AssertIsTrue(layer0 != null, "Layer 0 should be not null.");
AssertIsTrue(layer0.Name == "Layer 4", "The Name property of the layer 0 should be `Layer 4`");
AssertIsTrue(!layer0.IsTemplate, "The IsTemplate property of the layer 0 should be false.");
AssertIsTrue(layer0.IsLocked, "The IsLocked property of the layer 0 should be true.");
AssertIsTrue(layer0.IsShown, "The IsShown property of the layer 0 should be true.");
AssertIsTrue(layer0.IsPrinted, "The IsPrinted property of the layer 0 should be true.");
AssertIsTrue(!layer0.IsPreview, "The IsPreview property of the layer 0 should be false.");
AssertIsTrue(layer0.IsImagesDimmed, "The IsImagesDimmed property of the layer 0 should be true.");
AssertIsTrue(layer0.DimValue == 51, "The DimValue property of the layer 0 should be 51.");
AssertIsTrue(layer0.ColorNumber == 0, "The ColorNumber property of the layer 0 should be 0.");
AssertIsTrue(layer0.Red == 79, "The Red property of the layer 0 should be 79.");
AssertIsTrue(layer0.Green == 128, "The Green property of the layer 0 should be 128.");
AssertIsTrue(layer0.Blue == 255, "The Blue property of the layer 0 should be 255.");
AssertIsTrue(layer0.RasterImages.Length == 0, "The pixels length property of the raster image in the layer 0 should equals 0.");
AiLayerSection layer1 = image.Layers[1];
AssertIsTrue(layer1 != null, "Layer 1 should be not null.");
AssertIsTrue(layer1.Name == "Layer 1", "The Name property of the layer 1 should be `Layer 1`");
AssertIsTrue(layer1.RasterImages.Length == 1, "The length property of the raster images in the layer 1 should equals 1.");
AiRasterImageSection rasterImage = layer1.RasterImages[0];
AssertIsTrue(rasterImage != null, "The raster image in the layer 1 should be not null.");
AssertIsTrue(rasterImage.Pixels != null, "The pixels property of the raster image in the layer 1 should be not null.");
AssertIsTrue(string.Empty == rasterImage.Name, "The Name property of the raster image in the layer 1 should be empty");
AssertIsTrue(rasterImage.Pixels.Length == 100, "The pixels length property of the raster image in the layer 1 should equals 100.");
image.Save(outputFilePath + ".psd", new PsdOptions());
image.Save(outputFilePath + ".png", new PngOptions() { ColorType = PngColorType.TruecolorWithAlpha });
}
// 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 + @"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());
}
// 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 + @"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());
}
// 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 + @"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());
}
// 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 + @"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());
}
// 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());
}
// 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());
}
// 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 + @"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());
}
// 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));
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
// 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);
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
// 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);
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
string dataDir = baseFolder;
string outputDir = output;
// These examples demonstrate conversion of the PSD image format to other Color Modes/BitDepth.
ImageConversion(ColorModes.Grayscale, 16, 2);
ImageConversion(ColorModes.Grayscale, 8, 2);
ImageConversion(ColorModes.Grayscale, 8, 1);
ImageConversion(ColorModes.Rgb, 8, 4);
ImageConversion(ColorModes.Rgb, 16, 4);
ImageConversion(ColorModes.Cmyk, 8, 5);
ImageConversion(ColorModes.Cmyk, 16, 5);
void ImageConversion(ColorModes colorMode, short channelBitsCount, short channelsCount)
{
var compression = channelBitsCount > 8 ? CompressionMethod.Raw : CompressionMethod.RLE;
SaveToPsdThenLoadAndSaveToPng(
"SheetColorHighlightExample",
colorMode,
channelBitsCount,
channelsCount,
compression,
1);
SaveToPsdThenLoadAndSaveToPng(
"FillOpacitySample",
colorMode,
channelBitsCount,
channelsCount,
compression,
2);
SaveToPsdThenLoadAndSaveToPng(
"ClippingMaskRegular",
colorMode,
channelBitsCount,
channelsCount,
compression,
3);
}
// Saves to PSD then loads the saved file and saves to PNG.
void SaveToPsdThenLoadAndSaveToPng(
string file,
ColorModes colorMode,
short channelBitsCount,
short channelsCount,
CompressionMethod compression,
int layerNumber)
{
string srcFile = dataDir + file + ".psd";
string postfix = colorMode.ToString() + channelBitsCount + "bits" + channelsCount + "channels" +
compression;
string fileName = file + "_" + postfix + ".psd";
string exportPath = outputDir + fileName;
PsdOptions psdOptions = new PsdOptions()
{
ColorMode = colorMode,
ChannelBitsCount = channelBitsCount,
ChannelsCount = channelsCount,
CompressionMethod = compression
};
using (var image = (PsdImage)Image.Load(srcFile))
{
image.Convert(psdOptions);
RasterCachedImage raster = image.Layers.Length > 0 && layerNumber >= 0
? (RasterCachedImage)image.Layers[layerNumber]
: image;
Graphics graphics = new Graphics(raster);
int width = raster.Width;
int height = raster.Height;
Rectangle rect = new Rectangle(
width / 3,
height / 3,
width - (2 * (width / 3)) - 1,
height - (2 * (height / 3)) - 1);
graphics.DrawRectangle(new Pen(Color.DarkGray, 1), rect);
image.Save(exportPath);
}
string pngExportPath = Path.ChangeExtension(exportPath, "png");
using (PsdImage image = (PsdImage)Image.Load(exportPath))
{
image.Save(pngExportPath, new PngOptions() { ColorType = PngColorType.TruecolorWithAlpha });
}
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
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);
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
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 });
}
// 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);
}
// 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);
}
}
// 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 + @"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());
}
// 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 + "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());
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
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);
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
string destName = OutputDir + @"RenderTextWithDifferentColorsInTextLayer_out.png";
// Load the noisy image
using (var psdImage = (PsdImage)Image.Load(sourceFile))
{
var txtLayer = (TextLayer)psdImage.Layers[1];
txtLayer.TextData.UpdateLayerData();
PngOptions pngOptions = new PngOptions();
pngOptions.ColorType = PngColorType.TruecolorWithAlpha;
psdImage.Save(destName, pngOptions);
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
{
/// <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;
}
}
}
}
// 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 + "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());
}
// 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 + "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());
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
string sourceFileName = "sample_konstanting.psd";
string[] outputs = new string[]
{
"replacedfont0.tiff",
"replacedfont1.png",
"replacedfont2.jpg"
};
using (PsdImage image = (PsdImage)Image.Load(sourceFileName, new PsdLoadOptions()))
{
// This way you can use different fonts for different outputs
image.Save(outputs[0], new TiffOptions(TiffExpectedFormat.TiffJpegRgb) { DefaultReplacementFont = "Arial" });
image.Save(outputs[1], new PngOptions { DefaultReplacementFont = "Verdana" });
image.Save(outputs[2], new JpegOptions { DefaultReplacementFont = "Times New Roman" });
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
ImageOptionsBase saveOptions = new PngOptions();
InterruptMonitor monitor = new InterruptMonitor();
string source = "big2.psb";
string output = "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);
}
}
// 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
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
// Add color overlay layer effect at runtime
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);
}
// 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 + @"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);
}
// 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 + @"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);
}
// 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 + @"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);
}
// 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 + @"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());
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
var outputPath = dataDir + "ColorBalance_out.psd";
using (var im = (FileFormats.Psd.PsdImage)Image.Load(filePath))
{
foreach (var layer in im.Layers)
{
var cbLayer = layer as ColorBalanceAdjustmentLayer;
if (cbLayer != null)
{
cbLayer.ShadowsCyanRedBalance = 30;
cbLayer.ShadowsMagentaGreenBalance = -15;
cbLayer.ShadowsYellowBlueBalance = 40;
cbLayer.MidtonesCyanRedBalance = -90;
cbLayer.MidtonesMagentaGreenBalance = -25;
cbLayer.MidtonesYellowBlueBalance = 20;
cbLayer.HighlightsCyanRedBalance = -30;
cbLayer.HighlightsMagentaGreenBalance = 67;
cbLayer.HighlightsYellowBlueBalance = -95;
cbLayer.PreserveLuminosity = true;
}
}
im.Save(outputPath);
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
// 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]);
if (colorOverlay.Color != Color.Red ||
colorOverlay.Opacity != 153)
{
throw new Exception("Color overlay read wrong");
}
colorOverlay.Color = Color.Green;
colorOverlay.Opacity = 128;
im.Save(psdPathAfterChange);
}
// 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();
}
// 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 ...
}
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
// 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();
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
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);
}
// 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 + @"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());
}
// 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 + @"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());
}
// 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 + @"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());
}
// 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);
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
string sourceFileName = "sample_konstanting.psd";
string[] outputs = new string[]
{
"replacedfont0.tiff",
"replacedfont1.png",
"replacedfont2.jpg"
};
using (PsdImage image = (PsdImage)Image.Load(sourceFileName, new PsdLoadOptions()))
{
// This way you can use different fonts for different outputs
image.Save(outputs[0], new TiffOptions(TiffExpectedFormat.TiffJpegRgb) { DefaultReplacementFont = "Arial" });
image.Save(outputs[1], new PngOptions { DefaultReplacementFont = "Verdana" });
image.Save(outputs[2], new JpegOptions { DefaultReplacementFont = "Times New Roman" });
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
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");
}
// For complete examples and data files, please go to https://github.com/aspose-psd/Aspose.PSD-for-.NET
string destNameCubicConvolution = dataDir + "ResamplerCubicConvolutionStripes_after.psd";
// Load an existing image into an instance of PsdImage class
using (PsdImage image = (PsdImage)Image.Load(sourceFile))
{
image.Resize(300, 300, ResizeType.CubicConvolution);
image.Save(destNameCubicConvolution, new PsdOptions(image));
}
string destNameCatmullRom = dataDir + "ResamplerCatmullRomStripes_after.psd";
// Load an existing image into an instance of PsdImage class
using (PsdImage image = (PsdImage)Image.Load(sourceFile))
{
image.Resize(300, 300, ResizeType.CatmullRom);
image.Save(destNameCatmullRom, new PsdOptions(image));
}
string destNameMitchell = "ResamplerMitchellStripes_after.psd";
// Load an existing image into an instance of PsdImage class
using (PsdImage image = (PsdImage)Image.Load(sourceFile))
{
image.Resize(300, 300, ResizeType.Mitchell);