### Embedded Smart Object Layer Support Example Setup (C#)
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-20-9-release-notes
This C# code snippet sets up the initial parameters and an array of file formats for demonstrating embedded smart object layer support in PSD files. It defines constants for bounds and initializes an array with various image formats.
```csharp
// This example demonstrates how to change the smart object layer in the PSD file and export / update smart object original embedded contents.
string dataDir = "PSDNET615_1\";
const int left = 0;
const int top = 0;
const int right = 0xb;
const int bottom = 0x10;
FileFormat[] formats = new[]
{
FileFormat.Png, FileFormat.Psd, FileFormat.Bmp, FileFormat.Jpeg, FileFormat.Gif, FileFormat.Tiff, FileFormat.Jpeg2000
```
--------------------------------
### Regular Layer Content From Different Files Hash Test Setup in C#
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-22-6-release-notes
Sets up the test environment for comparing regular layer content hashes from different files. It defines the output directory and prepares for saving processed files. This is a foundational step for cross-file layer integrity checks.
```csharp
string outputFile = Path.Combine("output", fileName);
Directory.CreateDirectory("output");
```
--------------------------------
### Support Lnk2 Resource in PSD Files using C#
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-20-7-release-notes
Demonstrates how to get and set properties of the PSD Lnk2 Resource and its liFD data sources. It includes assertions for resource properties and saving smart object data. This example requires the Aspose.PSD library.
```csharp
void AssertAreEqual(object expected, object actual)
{
if (!object.Equals(actual, expected))
{
throw new FormatException(string.Format("Actual value {0} are not equal to expected {1}.", actual, expected));
}
}
object[] Lnk2ResourceSupportCases = new object[]
{
new object[]
{
"00af34a0-a90b-674d-a821-73ee508c5479",
"rgb8_2x2.png",
"png",
string.Empty,
0x53,
0d,
string.Empty,
7,
true,
0x124L,
0x74cL
}
};
object[] LayeredLnk2ResourceSupportCases = new object[]
{
new object[]
{
"69ac1c0d-1b74-fd49-9c7e-34a7aa6299ef",
"huset.jpg",
"JPEG",
string.Empty,
0x9d46,
0d,
"xmp.did:0F94B342065B11E395B1FD506DED6B07",
7,
true,
0x9E60L,
0xc60cL
},
new object[]
{
"5a7d1965-0eae-b24e-a82f-98c7646424c2",
"panama-papers.jpg",
"JPEG",
string.Empty,
0xF56B,
0d,
"xmp.did:BDE940CBF51B11E59D759CDA690663E3",
7,
true,
0xF694L,
0x10dd4L
},
};
object[] LayeredLnk3ResourceSupportCases = new object[]
{
new object[]
{
"2fd7ba52-0221-de4c-bdc4-1210580c6caa",
"panama-papers.jpg",
"JPEG",
string.Empty,
0xF56B,
0d,
"xmp.did:BDE940CBF51B11E59D759CDA690663E3",
7,
true,
0xF694l,
0x10dd4L
},
new object[]
{
"372d52eb-5825-8743-81a7-b6f32d51323d",
"huset.jpg",
"JPEG",
string.Empty,
0x9d46,
0d,
"xmp.did:0F94B342065B11E395B1FD506DED6B07",
7,
true,
0x9E60L,
0xc60cL
},
};
var basePath = @"PSDNET392_1\";
const string Output = "Output\";
// Saves the data of a smart object in PSD file to a file.
void SaveSmartObjectData(string prefix, string fileName, byte[] data)
{
var filePath = basePath + prefix + "_" + fileName;
using (var container = FileStreamContainer.CreateFileStream(filePath, false))
{
container.Write(data);
}
}
// Loads the new data for a smart object in PSD file.
byte[] LoadNewData(string fileName)
{
using (var container = FileStreamContainer.OpenFileStream(basePath + fileName))
{
return container.ToBytes();
}
}
// Gets and sets properties of the PSD Lnk2 / Lnk3 Resource and its liFD data sources in PSD image
void ExampleOfLnk2ResourceSupport(
string fileName,
int dataSourceCount,
int length,
int newLength,
object[] dataSourceExpectedValues)
{
using (PsdImage image = (PsdImage)Image.Load(basePath + fileName))
{
Lnk2Resource lnk2Resource = null;
foreach (var resource in image.GlobalLayerResources)
{
lnk2Resource = resource as Lnk2Resource;
if (lnk2Resource != null)
{
AssertAreEqual(lnk2Resource.DataSourceCount, dataSourceCount);
AssertAreEqual(lnk2Resource.Length, length);
AssertAreEqual(lnk2Resource.IsEmpty, false);
for (int i = 0; i < lnk2Resource.DataSourceCount; i++)
{
LiFdDataSource lifdSource = lnk2Resource[i];
object[] expected = (object[])dataSourceExpectedValues[i];
AssertAreEqual(LinkDataSourceType.liFD, lifdSource.Type);
AssertAreEqual(new Guid((string)expected[0]), lifdSource.UniqueId);
AssertAreEqual(expected[1], lifdSource.OriginalFileName);
AssertAreEqual(expected[2], lifdSource.FileType.TrimEnd(' '));
AssertAreEqual(expected[3], lifdSource.FileCreator.TrimEnd(' '));
AssertAreEqual(expected[4], lifdSource.Data.Length);
AssertAreEqual(expected[5], lifdSource.AssetModTime);
AssertAreEqual(expected[6], lifdSource.ChildDocId);
AssertAreEqual(expected[7], lifdSource.Version);
AssertAreEqual((bool)expected[8], lifdSource.HasFileOpenDescriptor);
AssertAreEqual(expected[9], lifdSource.Length);
if (lifdSource.HasFileOpenDescriptor)
{
AssertAreEqual(-1, lifdSource.CompId);
AssertAreEqual(-1, lifdSource.OriginalCompId);
lifdSource.CompId = int.MaxValue;
}
SaveSmartObjectData(
Output + fileName,
lifdSource.OriginalFileName,
lifdSource.Data);
}
}
}
}
}
```
--------------------------------
### Process Text in AI File and Save as PNG
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-25-8-release-notes
This example demonstrates how to load an AI file, process text within it, and save the result as a PNG image. It uses the AiImage class and PngOptions for saving.
```csharp
string sourceFile = Path.Combine(baseFolder, "text_test.ai");
string outputFile = Path.Combine(outputFolder, "text_test.png");
using (AiImage image = (AiImage)Image.Load(sourceFile))
{
image.Save(outputFile, new PngOptions());
}
```
--------------------------------
### Load PSB and save as Grayscale PNG
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-22-9-release-notes
Shows how to load a PSB (large document format) file and save it as a grayscale PNG with alpha channel. This example addresses potential exceptions during loading global layer resources.
```csharp
string sourcePsdFile = "input.psb";
string outputImageFile = "output.png";
using (var image = (PsdImage)Image.Load(sourcePsdFile))
{
// Here should be no exception.
image.Save(outputImageFile, new PngOptions() { ColorType = PngColorType.GrayscaleWithAlpha });
}
```
--------------------------------
### Add XPacket Metadata Support for AI Format
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-24-6-release-notes
This example demonstrates how to access and verify XMP metadata, specifically the 'CreatorTool' and page dimensions, from an AI (Adobe Illustrator) file using Aspose.PSD for .NET. It ensures that the metadata is correctly loaded and accessible.
```csharp
string sourceFile = Path.Combine(baseFolder, "ai_one.ai");
void AssertAreEqual(object expected, object actual)
{
if (!object.Equals(expected, actual))
{
throw new Exception("Objects are not equal.");
}
}
void AssertIsNotNull(object testObject)
{
if (testObject == null)
{
throw new Exception("Test object are null.");
}
}
string creatorToolKey = ":CreatorTool";
string nPagesKey = "xmpTPg:NPages";
string unitKey = "stDim:unit";
string heightKey = "stDim:h";
string widthKey = "stDim:w";
string expectedCreatorTool = "Adobe Illustrator CC 22.1 (Windows)";
string expectedNPages = "1";
string expectedUnit = "Pixels";
double expectedHeight = 768;
double expectedWidth = 1366;
using (AiImage image = (AiImage)Image.Load(sourceFile))
{
// Xmp Metadata was added.
var xmpMetaData = image.XmpData;
AssertIsNotNull(xmpMetaData);
// No we can get access to Xmp Packages of AI files.
var basicPackage = xmpMetaData.GetPackage(Namespaces.XmpBasic) as XmpBasicPackage;
var package = xmpMetaData.Packages[4];
// And we have access to the content of these packages.
var creatorTool = basicPackage[creatorToolKey].ToString();
var nPages = package[nPagesKey];
var unit = package[unitKey];
var height = double.Parse(package[heightKey].ToString(), CultureInfo.InvariantCulture);
var width = double.Parse(package[widthKey].ToString(), CultureInfo.InvariantCulture);
AssertAreEqual(creatorTool, expectedCreatorTool);
AssertAreEqual(nPages, expectedNPages);
AssertAreEqual(unit, expectedUnit);
AssertAreEqual(height, expectedHeight);
AssertAreEqual(width, expectedWidth);
}
```
--------------------------------
### Handle Image Loading Failures for AI Files
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-24-2-release-notes
Addresses an exception occurring during image loading for AI files. This example shows how to load multiple AI files and convert them to PNG format, indicating a fix for potential loading issues.
```csharp
string sourceFile1 = Path.Combine(baseFolder, "PRODUCT.ai");
string outputFile1 = Path.Combine(outputFolder, "PRODUCT.png");
using (AiImage image = (AiImage)Image.Load(sourceFile1))
{
image.Save(outputFile1, new PngOptions());
}
string sourceFile2 = Path.Combine(baseFolder, "Dolota.ai");
string outputFile2 = Path.Combine(outputFolder, "Dolota.png");
using (AiImage image = (AiImage)Image.Load(sourceFile2))
{
image.Save(outputFile2, new PngOptions());
}
string sourceFile3 = Path.Combine(baseFolder, "ARS_novelty_2108_out_01(1).ai");
string outputFile3 = Path.Combine(outputFolder, "ARS_novelty_2108_out_01(1).png");
using (AiImage image = (AiImage)Image.Load(sourceFile3))
{
image.Save(outputFile3, new PngOptions());
}
string sourceFile4 = Path.Combine(baseFolder, "bit_gear.ai");
string outputFile4 = Path.Combine(outputFolder, "bit_gear.png");
using (AiImage image = (AiImage)Image.Load(sourceFile4))
{
image.Save(outputFile4, new PngOptions());
}
string sourceFile5 = Path.Combine(baseFolder, "test.ai");
string outputFile5 = Path.Combine(outputFolder, "test.png");
using (AiImage image = (AiImage)Image.Load(sourceFile5))
{
image.Save(outputFile5, new PngOptions());
}
```
--------------------------------
### C# Export and Edit WebP to PSD with Aspose.PSD
Source: https://docs.aspose.com/psd/net/adapters/quick-start
This C# code snippet demonstrates how to create a new WebP image, edit it using Aspose.Imaging graphics functionalities, and then convert it to a PSD image. The resulting PSD image can be further edited with Photoshop-like features such as text layers and adjustment layers before saving. This example requires the Aspose.PSD and Aspose.Imaging libraries.
```csharp
using (WebPImage webp = new WebPImage(300, 300, null))
{
var gr = new Aspose.Imaging.Graphics(webp);
gr.Clear(Aspose.Imaging.Color.Wheat);
gr.DrawArc(
new Aspose.Imaging.Pen(Aspose.Imaging.Color.Black, 5),
new Aspose.Imaging.Rectangle(50, 50, 200, 200),
0,
270);
using (var psdImage = webp.ToPsdImage())
{
psdImage.AddTextLayer("Some text", new Rectangle(100, 100, 100, 50));
var hue = psdImage.AddHueSaturationAdjustmentLayer();
hue.Hue = 130;
psdImage.Save("output.psd");
}
}
```
--------------------------------
### Export PSD with Arc and Arch Warp Types using Aspose.PSD for .NET
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-23-7-release-notes
This example demonstrates exporting a PSD file that utilizes 'arc' and 'arch' warp transformations using Aspose.PSD for .NET. It loads the PSD files with warp settings and saves them as PNG images. This functionality requires the Aspose.PSD library to be installed.
```csharp
string sourceArcFile = "arc_warp.psd";
string outputArcFile = "arc_export.png";
string sourceArchFile = "arch_warp.psd";
string outputArchFile = "arch_export.png";
using (var psdImage = (PsdImage)Image.Load(sourceArcFile, new PsdLoadOptions() { AllowWarpRepaint = true, LoadEffectsResource = true }))
{
psdImage.Save(outputArcFile, new PngOptions
{
ColorType = PngColorType.TruecolorWithAlpha
});
}
```
--------------------------------
### Implement AI Blending Support
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-24-12-release-notes
This example implements blending support for AI files. It loads an AI file and saves it as a PNG, verifying that blending modes are correctly applied. Dependencies include Aspose.PSD for .NET. Inputs are an AI file path, and the output is a PNG file.
```csharp
string sourceFile = Path.Combine(baseFolder, "2238.ai");
string outputFile = Path.Combine(outputFolder, "2238.png");
using (AiImage image = (AiImage)Image.Load(sourceFile))
{
image.Save(outputFile, new PngOptions());
}
```
--------------------------------
### Implement Interrupt Monitor for Image Saving in C#
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-18-8-release-notes
This C# example shows how to use the InterruptMonitor for handling long-running image saving operations. It sets up a worker thread to save an image, starts the thread, and then interrupts the process after a short delay using the monitor. The thread is then joined to ensure it finishes cleanly after interruption.
```csharp
public void InterruptMonitorTest(string dir, string ouputDir)
{
ImageOptionsBase saveOptions = new ImageOptions.PngOptions();
Multithreading.InterruptMonitor monitor = new Multithreading.InterruptMonitor();
SaveImageWorker worker = new SaveImageWorker(dir + "big.psb", dir + "big_out.png", saveOptions, monitor);
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(worker.ThreadProc));
try
{
thread.Start();
// The timeout should be less than the time required for full image conversion (without interruption).
System.Threading.Thread.Sleep(3000);
// Interrupt the process
monitor.Interrupt();
System.Console.WriteLine("Interrupting the save thread #{0} at {1}", thread.ManagedThreadId, System.DateTime.Now);
// Wait for interruption...
thread.Join();
}
finally
{
```
--------------------------------
### Crop PSD Layers and Add New Layers
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-18-12-release-notes
This example illustrates how to work with layers in a PSD file, specifically focusing on cropping and adding new layers. It loads a PSD, retrieves layer bounds and pixel data, and then adds multiple new regular layers, suggesting a workflow for manipulating existing layer content and structure.
```csharp
// Possible: Crop methods in the Aspose.Psd don't work
string sourceFileName = "SourceFile.psd";
string exportPath = "SourceFileEdited.psd";
string exportPathPng = "SourceFileEdited.png";
using (var image = (PsdImage)Image.Load(sourceFileName))
{
var oldLayer = image.Layers[0];
var oldBounds = oldLayer.Bounds;
var oldLayerData = image.Layers[0].LoadArgb32Pixels(oldBounds);
var layers = new Layer[4];
for (int i = 0; i < 4; i++)
{
layers[i] = image.AddRegularLayer();
```
--------------------------------
### PSD File Exception Handling with LnkE Resource using Aspose.PSD for .NET
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-20-7-release-notes
This example provides utility methods for assertions and demonstrates a complex data structure representing cases for compound LnkE Resource support, including the adobeStockLicenseState property. This is in the context of addressing exceptions on loading specific PSD files with these features.
```csharp
void AssertIsTrue(bool condition)
{
if (!condition)
{
throw new FormatException(message);
}
}
void AssertAreEqual(object actual, object expected)
{
if (!object.Equals(actual, expected))
{
throw new FormatException(message);
}
}
object[] ComplexLnkEResourceSupportCases = new object[]
{
new object[]
{
"10fc87d0-688f-1179-9685-9d0a040abdc3",
@"CC Libraries Asset “OneReview-InDesign-InContextTranslation/or hdr btns” (Feature is available in Photoshop CC 2015)",
"01/01/0001 00:00:00",
1463698633541.0d,
"uuid:8485ca8d-9496-7f4d-9ef7-4243a00d4161",
"OneReview-InDesign-InContextTranslation",
"or hdr btns.ai",
0L,
"",
6,
"unlicensed",
false,
0x3b4
},
new object[]
{
"10fc87cc-688f-1179-9685-9d0a040abdc3",
@"CC Libraries Asset “OneReview-InDesign-InContextTranslation/cs Id icon” (Feature is available in Photoshop CC 2015)",
"01/01/0001 00:00:00",
1463698633512.0d,
"uuid:c18be832-adf7-4b43-8223-a9740807a66c",
"OneReview-InDesign-InContextTranslation",
"cs Id icon.ai",
0L,
"",
6,
"unlicensed",
false,
0x3b0
},
new object[]
{
"10fef79c-688f-1179-9685-9d0a040abdc3",
@"CC Libraries Asset “OneReview-InDesign-InContextTranslation/pointer cursor” (Feature is available in Photoshop CC 2015)",
"01/01/0001 00:00:00",
1463698633570.0d,
"uuid:9d7ccaac-f094-214b-8721-1a07ae8700a9",
"OneReview-InDesign-InContextTranslation",
"pointer cursor.ai",
0L,
"",
6,
"unlicensed",
false,
0x03c0
},
new object[]
{
"10fef79a-688f-1179-9685-9d0a040abdc3",
@"CC Libraries Asset “OneReview-InDesign-InContextTranslation/x” (Feature is available in Photoshop CC 2015)",
"01/01/0001 00:00:00",
1463698633555.0d,
"uuid:b28aa699-21d6-2d4d-a4c7-790234c1b6ba",
"OneReview-InDesign-InContextTranslation",
"x.ai",
0L,
"",
6,
"unlicensed",
false,
0x38c
},
new object[]
{
"10fef79b-688f-1179-9685-9d0a040abdc3",
@"CC Libraries Asset “OneReview-InDesign-InContextTranslation/modal btns” (Feature is available in Photoshop CC 2015)",
"01/01/0001 00:00:00",
1463698633562.0d,
"uuid:1bd42767-058d-da44-bdee-eada3b9d40a5",
"OneReview-InDesign-InContextTranslation",
"modal btns.ai",
0L,
"",
6,
"unlicensed",
false,
0x03c0
}
};
```
--------------------------------
### Get LayerGroup Left and Top Positions
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-23-7-release-notes
Loads a PSD file and iterates through its layers. For each LayerGroup, it calculates and asserts the correct Left, Top, Right, and Bottom positions based on its inner layers.
```csharp
string sourceFile = "layerGroupFigures.psd";
void AssertAreEqual(object expected, object actual)
{
if (!object.Equals(expected, actual))
{
throw new Exception("Objects are not equal.");
}
}
using (var image = (PsdImage)Image.Load(sourceFile))
{
var layers = image.Layers;
for (int i = 0; i < layers.Length; i++)
{
var layer = layers[i];
if (layer is LayerGroup)
{
// Getting LayerGroup.
var group = (LayerGroup)layer;
var expectedLeft = int.MaxValue;
var expectedTop = int.MaxValue;
var expectedRight = 0;
var expectedBottom = 0;
// Calculating real Left, Top, Right, and Bottom positions.
foreach (var innerLayer in group.Layers)
{
if (innerLayer is AdjustmentLayer || innerLayer.Bounds.IsEmpty)
{
continue;
}
expectedLeft = Math.Min(expectedLeft, innerLayer.Left);
expectedTop = Math.Min(expectedTop, innerLayer.Top);
expectedRight = Math.Max((expectedLeft + group.Width), (innerLayer.Left + innerLayer.Width));
expectedBottom = Math.Max((expectedTop + group.Height), (innerLayer.Top + innerLayer.Height));
}
// LayerGroup Left, Top, Right, and Bottom positions are calculated properly now.
AssertAreEqual(group.Left, expectedLeft);
AssertAreEqual(group.Top, expectedTop);
AssertAreEqual(group.Right, expectedRight);
AssertAreEqual(group.Bottom, expectedBottom);
}
}
}
```
--------------------------------
### Replace Default Font in PSD Image with Aspose.PSD in C#
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-20-6-release-notes
This example shows how to load a PSD file and manage font replacements, specifically targeting a default replacement font setting. The test is designed to work even if a specific font ('Konstanting') is not installed, ensuring the replacement mechanism functions correctly across different output formats like TIFF, PNG, and JPG.
```csharp
// Please, don't install Konstanting Font, because this test should replace font that is not installed
string sourceFileName = "sample_konstanting.psd";
string[] outputs = new string[]
{
"replacedfont0.tiff",
"replacedfont1.png",
"replacedfont2.jpg"
};
using (PsdImage image = (PsdImage)Image.Load(sourceFileName, new PsdLoadOptions()))
{
// Code to save the image with font replacement would follow here
}
```
--------------------------------
### Export AI to PNG and GIF with Various Backgrounds and Alpha Settings
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-25-8-release-notes
This example illustrates exporting an AI file to multiple PNG and GIF formats, controlling background color (white or transparent) and alpha channel settings to achieve different output appearances.
```csharp
string sourceFile = Path.Combine(baseFolder, "rect2_color.ai");
string outPng_WithAlpha_Back_White = Path.Combine(outputFolder, "output_WithAlpha_Back_White.png");
string outPng_WithAlpha_Back_Transparent = Path.Combine(outputFolder, "output_WithAlpha_Back_Transparent.png");
string outPng_NoAlpha_Back_Transparent = Path.Combine(outputFolder, "output_NoAlpha_Back_Transparent.png");
string outGif_Back_Transparent = Path.Combine(outputFolder, "output_Back_Transparent.gif");
string outGif_Back_White = Path.Combine(outputFolder, "output_Back_White.gif");
using (AiImage image = (AiImage)Image.Load(sourceFile))
{
// AiImage.BackgroundColor = White, Png file with Alpha
// We should get White background
image.Save(outPng_WithAlpha_Back_White, new PngOptions() { ColorType = PngColorType.TruecolorWithAlpha });
// AiImage.BackgroundColor = Transparent, Png file with Alpha
// We should get Transparent background
image.BackgroundColor = Color.Transparent;
image.Save(outPng_WithAlpha_Back_Transparent, new PngOptions() { ColorType = PngColorType.TruecolorWithAlpha });
// AiImage.BackgroundColor = Transparent, Png file without Alpha
// We should get black background
image.Save(outPng_NoAlpha_Back_Transparent, new PngOptions());
// AiImage.BackgroundColor = Transparent, Gif file
// We should get black background
image.Save(outGif_Back_Transparent, new GifOptions() { DoPaletteCorrection = false });
// AiImage.BackgroundColor = White, Gif file
// We should get White background
image.BackgroundColor = Color.White;
image.Save(outGif_Back_White, new GifOptions() { DoPaletteCorrection = false });
}
```
--------------------------------
### Update Font Cache with Aspose.Drawing
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-24-7-release-notes
Demonstrates how to refresh the font cache and check the count of installed fonts using Aspose.Drawing. This addresses issues with fonts not loading correctly. It prints the font count before and after the update and checks the platform.
```csharp
using (var installedFonts = new System.Drawing.Text.InstalledFontCollection())
{
Console.WriteLine("- Before update. Installed fonts count: " + installedFonts.Families.Length);
Console.WriteLine("- Platform: " + Environment.OSVersion.Platform.ToString());
Console.WriteLine("- Refresh the font cache by trying to get the Adobe font name for 'Arial': "
FontSettings.GetAdobeFontName("Arial"));
Console.WriteLine("- After update. Installed fonts count: " + installedFonts.Families.Length);
Assert.Greater(installedFonts.Families.Length, 1);
}
```
--------------------------------
### PSD File Processing Setup - C#
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-20-8-release-notes
This C# code sets up the necessary file paths and an array of expected values for processing a PSD file. It defines the source and output file paths and initializes the expectedValues array used in subsequent assertions.
```csharp
string dataDir = "PSDNET400_1\\";
var sourceFilePath = dataDir + "LayeredSmartObjects8bit2.psd";
var outputFilePath = dataDir + "LayeredSmartObjects8bit2_output.psd";
var expectedValues = new object[]
```
--------------------------------
### Apply Wave, Shell Up, and Shell Down Warps in PSD with Aspose.PSD
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-23-11-release-notes
This example illustrates how to load PSD files and apply different warp transformations like Wave, Shell Up, and Shell Down using Aspose.PSD. It configures load and save options for handling warps and effects, then saves the results as PNG. The Aspose.PSD library is a prerequisite.
```csharp
var loadOptions = new PsdLoadOptions() { AllowWarpRepaint = true, LoadEffectsResource = true };
var saveOptions = new PngOptions { ColorType = PngColorType.TruecolorWithAlpha };
string sourceFileFish = Path.Combine(baseFolder, "1752_warp_fish.psd");
string sourceFileRise = Path.Combine(baseFolder, "1752_warp_rise.psd");
string sourceFileWave = Path.Combine(baseFolder, "1752_warp_wave.psd");
string outputFileFish = Path.Combine(outputFolder, "1752_output_fish.png");
string outputFileRise = Path.Combine(outputFolder, "1752_output_rise.png");
string outputFileWave = Path.Combine(outputFolder, "1752_output_wave.png");
using (var psdImage = (PsdImage)Image.Load(sourceFileFish, loadOptions))
{
psdImage.Save(outputFileFish, saveOptions);
}
using (var psdImage = (PsdImage)Image.Load(sourceFileRise, loadOptions))
{
psdImage.Save(outputFileRise, saveOptions);
}
using (var psdImage = (PsdImage)Image.Load(sourceFileWave, loadOptions))
{
psdImage.Save(outputFileWave, saveOptions);
}
```
--------------------------------
### Get Unique Hash for Similar Layers - Aspose.PSD for .NET
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-22-6-release-notes
Provides examples of how to generate unique content hashes for various layer types (Regular, Fill, Smart Object, Adjustment, Text, Group) within PSD files using Aspose.PSD for .NET. This functionality helps identify similar layers across different files. It includes helper methods for layer retrieval and hash comparisons.
```csharp
using Aspose.PSD;
using Aspose.PSD.FileFormats.Psd;
using Aspose.PSD.FileFormats.Psd.Layers;
using Aspose.PSD.ImageLoadOptions;
public class Program
{
static void Main()
{
RegularLayerContentHashTest("OnlyRegular.psd");
FillLayerContentHashTest("FillSmartGroup.psd");
SmartObjectLayerContentHashTest("FillSmartGroup.psd");
AdjustmentLayersContentHashTest("AllAdjustments.psd");
TextLayersContentHashTest("TextLayers.psd");
GroupLayerContentHashTest("FillSmartGroup.psd");
var contentTestFiles = new string[] { "OnlyRegular.psd", "FillSmartGroup.psd", "TextLayers.psd", "AllAdjustments.psd" };
foreach (var file in contentTestFiles)
{
RegularLayerContentFromDifferentFilesHashTest(file);
}
}
///
/// Gets the name of the layer by.
///
///
/// The image.
/// The name.
///
private static T GetLayerByName(PsdImage image, string name) where T : Layer
{
var layers = image.Layers;
foreach (var layer in layers)
{
if (layer.Name == name)
{
return (T)layer;
}
}
return null;
}
///
/// Ares the not equal.
///
///
/// The expected.
/// The actual.
/// Arguments must not be equal
public static void AreNotEqual(T expected, T actual)
{
if (expected != null && expected.Equals(actual))
{
throw new Exception("Arguments must not be equal");
}
}
///
/// Ares the equal.
///
///
/// The expected.
/// The actual.
/// Arguments must be equal
public static void AreEqual(T expected, T actual)
{
if (expected != null && !expected.Equals(actual))
{
throw new Exception("Arguments must be equal");
}
}
///
/// Regulars the layer content hash test.
///
/// Name of the file.
public static void RegularLayerContentHashTest(string fileName)
{
using (var im = (PsdImage)Image.Load(fileName))
{
var layers = new Layer[9];
var hashers = new LayerHashCalculator[9];
for (int i = 0; i < layers.Length; i++)
{
layers[i] = GetLayerByName(im, string.Format("Layer {0}", i + 1));
hashers[i] = new LayerHashCalculator(layers[i]);
}
AreNotEqual(hashers[0].GetChannelsHash(), hashers[1].GetChannelsHash());
AreNotEqual(hashers[1].GetChannelsHash(), hashers[2].GetChannelsHash());
AreNotEqual(hashers[0].GetChannelsHash(), hashers[2].GetChannelsHash());
AreNotEqual(hashers[5].GetChannelsHash(), hashers[7].GetChannelsHash());
AreNotEqual(hashers[0].GetChannelsHash(), hashers[8].GetChannelsHash());
// These layers' hashes are equal
AreEqual(hashers[0].GetChannelsHash(), hashers[3].GetChannelsHash());
AreEqual(hashers[1].GetChannelsHash(), hashers[4].GetChannelsHash());
AreEqual(hashers[0].GetChannelsHash(), hashers[6].GetChannelsHash());
// Check the blending mode hash
AreEqual(hashers[0].GetBlendingHash(), hashers[3].GetBlendingHash());
AreEqual(hashers[1].GetBlendingHash(), hashers[4].GetBlendingHash());
AreNotEqual(hashers[0].GetBlendingHash(), hashers[6].GetBlendingHash());
// But pointers are different
AreNotEqual(layers[0], layers[3]);
AreNotEqual(layers[1], layers[4]);
AreNotEqual(layers[0], layers[6]);
}
}
///
/// Fills the layer content hash test.
///
/// Name of the file.
public static void FillLayerContentHashTest(string fileName)
{
```
--------------------------------
### Apply Aspose.PSD and Adaptee Licenses in C#
Source: https://docs.aspose.com/psd/net/adapters/full-manual
This code demonstrates how to apply licenses for Aspose.PSD and an 'adaptee' product (Aspose.Imaging) using their respective License objects. Ensure you have the correct .lic files for both products. Licenses should ideally be applied once during project initialization.
```csharp
var license = new Aspose.PSD.License();
license.SetLicense(@"Aspose.PSD.NET.lic");
var licImaging = new Aspose.Imaging.License();
licImaging.SetLicense(@"Aspose.Imaging.NET.lic");
```
--------------------------------
### Load Specific PSD File for Export using Aspose.PSD
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-24-4-release-notes
This code snippet shows the initial step of loading a specific PSD file that might have export issues with Aspose.PSD. It serves as a starting point for diagnosing and fixing export problems.
```csharp
string sourceFile = Path.Combine(baseFolder, "1966source.psd");
```
--------------------------------
### Convert PSD to 32-bit and Save to PNG (.NET)
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-23-5-release-notes
This example demonstrates loading a PSD file (RGB/8bit or RGB/16bit), saving it as a 32-bit PSD file, and then loading the 32-bit PSD to save it as a PNG with alpha channel. This is useful for preserving or converting color depth and format.
```csharp
string inputFile = "input_8bit_rle.psd";
string outputPsdFile = "output_32bit.psd";
string outputImageFile32 = "output_from_32bit.png";
using (PsdImage srcImg = (PsdImage)Image.Load(inputFile))
{
PsdOptions totalOptions = new PsdOptions() { ChannelBitsCount = 32, ColorMode = ColorModes.Rgb };
srcImg.Save(outputPsdFile, totalOptions);
using (var img32 = Image.Load(outputPsdFile))
{
img32.Save(outputImageFile32, new PngOptions() { ColorType = PSD.FileFormats.Png.PngColorType.TruecolorWithAlpha });
}
}
```
--------------------------------
### Get Inline Formatting of TextLayer using C#
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-19-11-release-notes
This C# code snippet shows how to load a PSD file, iterate through its layers, and extract inline formatting details from text layers. It categorizes text portions into regular, bold, and italic based on font styles.
```csharp
using (var psdImage = (PsdImage)Image.Load("inline_formatting.psd"))
{
List regularText = new List();
List boldText = new List();
List italicText = new List();
var layers = psdImage.Layers;
for (int index = 0; index < layers.Length; index++)
{
var layer = layers[index];
if (!(layer is TextLayer))
{
continue;
}
var textLayer = (TextLayer)layer;
// gets fonts that contains in text layer
var fonts = textLayer.GetFonts();
var textPortions = textLayer.TextData.Items;
foreach (var textPortion in textPortions)
{
TextFontInfo font = fonts[textPortion.Style.FontIndex];
if (font != null)
{
switch (font.Style)
{
case FontStyle.Regular:
regularText.Add(textPortion);
break;
case FontStyle.Bold:
boldText.Add(textPortion);
break;
case FontStyle.Italic:
italicText.Add(textPortion);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
}
```
--------------------------------
### Convert PSD to PNG with License and Verbose Log
Source: https://docs.aspose.com/psd/net/cli/nlp-editor
An example demonstrating how to convert a PSD file to PNG format with transparency, apply a license, and enable verbose logging. The license only needs to be specified once.
```bash
nlp.cli Convert file from this folder to png format with alpha --license "C:\Aspose\LicenseFile.lic" --verbose
```
--------------------------------
### Apply Aspose.PSD License from File (.NET)
Source: https://docs.aspose.com/psd/net/licensing
Demonstrates how to apply an Aspose.PSD license using a license file. The license file should be placed in the same folder as the Aspose.PSD.dll or its path specified. This method is suitable for most .NET applications.
```csharp
using Aspose.PSD;
// Instantiate an instance of license and apply the license using a full path
Aspose.PSD.License license = new Aspose.PSD.License();
license.SetLicense("Aspose.PSD.lic");
```
--------------------------------
### Dockerfile Configuration for Aspose.PSD Application
Source: https://docs.aspose.com/psd/net/how-to-run-aspose-psd-in-docker
A Dockerfile example for building a .NET 6 application that uses Aspose.PSD. It specifies the base runtime image, sets the working directory, and includes commands for installing essential packages like apt-transport-https, libgdiplus, and libc6-dev, which are necessary for text rendering on Linux.
```dockerfile
FROM mcr.microsoft.com/dotnet/runtime:6.0 AS base
WORKDIR /app
# Install necessary packages for text rendering on Linux
RUN apt-get update && apt-get install -y --no-install-recommends \
apt-transport-https \
libgdiplus \
libc6-dev \
&& rm -rf /var/lib/apt/lists/*
# Copy application files
COPY . .
# Expose port if your application needs it (e.g., for web apps)
# EXPOSE 80
# Set the entry point for the container
ENTRYPOINT ["dotnet", "YourApplicationName.dll"]
```
--------------------------------
### Add Layer and Get ID from PSD Image (.NET)
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-23-7-release-notes
Shows how to add a new layer to a PSD image using the default constructor and retrieve its unique ID. This addresses an issue where default resources were not added, potentially causing NullReferenceExceptions. It utilizes PsdImage and Layer classes.
```.cs
string output = "newLayer.psd";
using (var psdImage = new PsdImage(500, 500))
{
var layer = new Layer();
psdImage.AddLayer(layer);
LyidResource lyidResource = (LyidResource)FindResource(LyidResource.TypeToolKey, layer.Resources);
int layerId = lyidResource.Value; // Was NullReferenceException
psdImage.Save(output);
}
```
--------------------------------
### Support blwh Resource (Black & White Adjustment Layer Data) in PSD using Aspose.PSD for .NET
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-20-2-release-notes
This example demonstrates how to support the blwh resource, which contains Black & White adjustment layer data. It loads a PSD, iterates through layers and resources to find the blwh resource, and asserts its properties. Requires Aspose.PSD for .NET.
```csharp
const string ActualPropertyValueIsWrongMessage = "Expected property value is not equal to actual value";
void AssertIsTrue(bool condition, string message)
{
if (!condition)
{
throw new FormatException(message);
}
}
void ExampleSupportOfBlwhResource(
string sourceFileName,
int reds,
int yellows,
int greens,
int cyans,
int blues,
int magentas,
bool useTint,
int bwPresetKind,
string bwPresetFileName,
double tintColorRed,
double tintColorGreen,
double tintColorBlue,
int tintColor,
int newTintColor)
{
string destinationFileName = "Output" + sourceFileName;
bool isRequiredResourceFound = false;
using (PsdImage im = (PsdImage)Image.Load(sourceFileName))
{
foreach (var layer in im.Layers)
{
foreach (var layerResource in layer.Resources)
{
if (layerResource is BlwhResource)
{
var blwhResource = (BlwhResource)layerResource;
var blwhLayer = (BlackWhiteAdjustmentLayer)layer;
isRequiredResourceFound = true;
AssertIsTrue(blwhResource.Reds == reds, ActualPropertyValueIsWrongMessage);
AssertIsTrue(blwhResource.Yellows == yellows, ActualPropertyValueIsWrongMessage);
AssertIsTrue(blwhResource.Greens == greens, ActualPropertyValueIsWrongMessage);
AssertIsTrue(blwhResource.Cyans == cyans, ActualPropertyValueIsWrongMessage);
AssertIsTrue(blwhResource.Blues == blues, ActualPropertyValueIsWrongMessage);
AssertIsTrue(blwhResource.Magentas == magentas, ActualPropertyValueIsWrongMessage);
AssertIsTrue(blwhResource.UseTint == useTint, ActualPropertyValueIsWrongMessage);
AssertIsTrue(blwhResource.TintColor == tintColor, ActualPropertyValueIsWrongMessage);
AssertIsTrue(blwhResource.BwPresetKind == bwPresetKind, ActualPropertyValueIsWrongMessage);
AssertIsTrue(blwhResource.BlackAndWhitePresetFileName == bwPresetFileName, ActualPropertyValueIsWrongMessage);
AssertIsTrue(Math.Abs(blwhLayer.TintColorRed - tintColorRed) < 1e-6, ActualPropertyValueIsWrongMessage);
AssertIsTrue(Math.Abs(blwhLayer.TintColorGreen - tintColorGreen) < 1e-6, ActualPropertyValueIsWrongMessage);
```
--------------------------------
### Enable Loaders and Exporters with Aspose.PSD Adapters for .NET
Source: https://docs.aspose.com/psd/net/adapters/quick-start
This code snippet demonstrates how to enable loading for specific file formats (SVG, WebP) and all exporters using Aspose.PSD Adapters for .NET. It also shows how to set licenses for Aspose.PSD and Aspose.Imaging, and then load and save an image.
```csharp
// This code allows to load the specified formats
Aspose.PSD.Adapters.Imaging.EnableLoaders(
FileFormat.Svg,
FileFormat.Webp);
// This code allows you to export using adapters
Aspose.PSD.Adapters.Imaging.EnableExporters();
// To work with adapters you need both Aspose.PSD and adaptee Licenses
var license = new Aspose.PSD.License();
license.SetLicense(@"Aspose.PSD.NET.lic");
var licImaging = new Aspose.Imaging.License();
licImaging.SetLicense(@"Aspose.Imaging.NET.lic");
// Aspose.Imaging loading and integration with PSD format will be provided seamless in this case.
using (var image = Image.Load(@"SomeFile.Webp"))
{
// Saving in this example is provided by Aspose.PSD
image.Save(@"output.png", new PngOptions() { ColorType = Aspose.PSD.FileFormats.Png.PngColorType.TruecolorWithAlpha });
}
```
--------------------------------
### Convert PSB to JPG and Save as PSB with Aspose.PSD for .NET
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-19-6-release-notes
This example addresses an issue where converting PSB to JPG might hang. It iterates through several PSB files, loads them using PsdLoadOptions, and saves them as JPG with a specified quality and also re-saves them as PSB. This helps in debugging and ensuring the conversion process completes successfully.
```csharp
Copy // Conversion PSB to JPG hangs
string[] sourceFileNames = new string[] {
//Test files with layers
"Little",
"Simple",
//Test files without layers
"psb",
"psb3"
};
var options = new PsdLoadOptions();
foreach (var fileName in sourceFileNames)
{
var sourceFileName = fileName + ".psb";
using (PsdImage image = (PsdImage)Image.Load(sourceFileName, options))
{
// All jpeg and psd files must be readable
image.Save(fileName + "_output.jpg", new JpegOptions() { Quality = 95 });
image.Save(fileName + "_output.psb");
}
}
```
--------------------------------
### Load and Save PSD Image with Options (.NET)
Source: https://docs.aspose.com/psd/net/aspose-psd-for-net-23-5-release-notes
Demonstrates how to load a PSD file with specific load options (AllowWarpRepaint) and save it to a PNG format with specified color type. This snippet requires the Aspose.PSD library.
```csharp
string sourceFile = "Bottom_Right.psd";
string outputFile = "output.png";
using (var image = (PsdImage)Image.Load(sourceFile, new PsdLoadOptions { AllowWarpRepaint = true }))
{
image.Save(outputFile, new PngOptions { ColorType = PngColorType.TruecolorWithAlpha});
}
```