NullReferenceException when trying to add existing Layer to new PsdImage

I am trying to take an existing layer from a loaded PsdImage and copy it to a fresh PsdImage to export it separately from the original PsdImage. The code has ran fine mostly, but I have ran into a new issue where in the middle of runtime, a NullReferenceException is thrown due to the layer being passed as a parameter to newImage.AddLayer(). When viewing my local variables at the time the exception is thrown, both newImage and the layer point to existing objects. This is the immediate section of my code where the issue is arising:

if (newImage != null)
{
    if (layer != null)
    {
        newImage.AddLayer(layer);
    }
}

I know that newImage and layer point to valid objects because I can view their values in my local variable view at the time of the exception. I am able to save layer by itself immediately before I call AddLayer with the following line of code:

layer.Save(exportPath + layer.Name + ".png", new PngOptions());

And if I pass a copy of layer as a parameter, that also does not crash:

newImage.AddLayer(new PsdLayer.Layer(layer));

While the above line doesn’t crash the program, it also doesn’t preserve the effects of the given layer when the new PsdLayer.Layer is made, which I need in newImage. I am at a loss here on why this error is occurring, especially since this section of code runs several times prior to crashing during runtime.

The following is the call stack within Aspose’s .dll when the error occurs

	Aspose.PSD.dll!Aspose.PSD.FileFormats.Psd.PsdImage.(Aspose.PSD.FileFormats.Psd.Layers.SmartObjects.SmartObjectLayer )	Unknown
 	Aspose.PSD.dll!Aspose.PSD.FileFormats.Psd.PsdImage.(Aspose.PSD.FileFormats.Psd.Layers.Layer , int )	Unknown
 	Aspose.PSD.dll!Aspose.PSD.FileFormats.Psd.PsdImage.AddLayer(Aspose.PSD.FileFormats.Psd.Layers.Layer layer)	Unknown

The NullReferenceException you are encountering when trying to add an existing layer to a new PsdImage could be due to several reasons, even if both newImage and layer appear to be valid objects at the time of the exception.

Here are a few suggestions to troubleshoot and potentially resolve the issue:

  1. Check Layer Type: Ensure that the layer you are trying to add is of a type that is supported by the AddLayer method. If the layer is a special type (like a Smart Object layer), it might require specific handling.

  2. Layer State: Verify that the layer is in a valid state to be added. Sometimes, layers may have properties or states that prevent them from being added to another image.

  3. Debugging: Since you mentioned that the code runs fine several times before crashing, consider adding additional logging or breakpoints to inspect the state of the layer just before the AddLayer call. This might help identify any changes in the layer’s state that could lead to the exception.

  4. Creating a New Layer: As a workaround, you can create a new layer based on the existing layer’s data, as you have done with new PsdLayer.Layer(layer). However, if this does not preserve the effects you need, you may need to manually copy the properties and resources from the original layer to the new layer.

  5. Background Layer Handling: If your PsdImage does not have any layers initially, it might be necessary to add a regular layer first to unlock the background layer, as the background layer is often treated differently in PSD files. You can add a temporary layer and then remove it to ensure the background layer is accessible.

Here’s a code snippet that demonstrates how to add a temporary layer to unlock the background layer:

if (newImage != null)
{
    // Add a temporary layer to unlock the background layer
    newImage.AddRegularLayer();
    
    // Now add the existing layer
    if (layer != null)
    {
        newImage.AddLayer(layer);
    }
}

By following these steps, you should be able to identify the cause of the NullReferenceException and successfully add the layer to your new PsdImage. If the issue persists, consider reaching out to Aspose support with detailed information about the layer type and state for further assistance.

@Skeletax Could you please provide input file and/or if it’s possible, simple project to reproduce this issue. Also, please provide version of Aspose.PSD do you use and OS.

We need to make investigation, but as a quick response, please check the following:
Effects are stored in the global resources of PsdImage, so, they should be copied to new image too.

To load Effects, you should use LoadEffectsResource property:

Image.Load(psdStream, new PsdLoadOptions { LoadEffectsResource = true });

I am using Aspose.PSD 24.7.0 on Windows 10. I have an example .psd file that provokes this error in this Google Drive: NullReferenceException Issue - Google Drive

I am using LoadEffectsResource (and AllowWarpRepaint) and it is still causing an error.

Below is a stack trace when this issue occurs with the provided .psd file:

System.NullReferenceException: Object reference not set to an instance of an object.
   at Aspose.PSD.FileFormats.Psd.PsdImage.(SmartObjectLayer )
   at Aspose.PSD.FileFormats.Psd.PsdImage.(Layer , Int32 )
   at Aspose.PSD.FileFormats.Psd.PsdImage.AddLayer(Layer layer)
   at PSD_Exporter.App.Exporter.SaveInformationRecursive(ViewToModel viewElements, PsdImage psdImage, LayerNode parent, StreamWriter iniFile, PsdImage mergeImage) in ...\Application\PSD_Exporter.App\Exporter.cs:line 780
   at PSD_Exporter.App.Exporter.SaveInformationRecursive(ViewToModel viewElements, PsdImage psdImage, LayerNode parent, StreamWriter iniFile, PsdImage mergeImage) in ...\Application\PSD_Exporter.App\Exporter.cs:line 736
   at PSD_Exporter.App.Exporter.SaveInformationRecursive(ViewToModel viewElements, PsdImage psdImage, LayerNode parent, StreamWriter iniFile, PsdImage mergeImage) in ...\Application\PSD_Exporter.App\Exporter.cs:line 714
   at PSD_Exporter.App.Exporter.SaveInformationRecursive(ViewToModel viewElements, PsdImage psdImage, LayerNode parent, StreamWriter iniFile, PsdImage mergeImage) in ...\Application\PSD_Exporter.App\Exporter.cs:line 744
   at PSD_Exporter.App.Exporter.SaveInformation(ViewToModel viewElements, PsdImage psdImage) in ...\Application\PSD_Exporter.App\Exporter.cs:line 677
   at PSD_Exporter.App.Exporter.AttemptExportPSDFile(ViewToModel viewElements) in ...\Application\PSD_Exporter.App\Exporter.cs:line 303
   at PSD_Exporter.Design.Form_Main.<beginExportButton_Click>b__3_0() in ...\Application\PSD_Exporter.Design\MainForm.cs:line 85

@Skeletax
We have opened the following new ticket(s) in our internal issue tracking system with high priority and will deliver their fixes according to the terms mentioned in Free Support Policies.

Issue ID(s): PSDNET-2155

You can obtain Paid Support Services if you need support on a priority basis, along with the direct access to our Paid Support management team.

@Dmitriy.Sorokin I have uploaded a version of my code that provokes this error in the Google Drive that was shared in my previous reply, also quoted below.

I’ve update Task with your code sample. Thank you, you will be notified when the issue will be fixed, or if there can be any workaround.