La automatización del reemplazo de objetos inteligentes le ayuda a crear variaciones del mismo modelo de Photoshop con diferentes imágenes. con Aspose.PSD para .NET se puede cargar un PSD, localizar las capas de objeto inteligente, sustituir sus contenidos incorporados con una nueva imagen, y salvar el documento actualizado.

Prerequisitos

  • .NET 6 o más tarde
  • El NuGet: Aspose.PSD
dotnet add package Aspose.PSD

Substituir el primer objeto inteligente en un PSD

Este ejemplo carga un PSD, encuentra el primero SmartObjectLayer, sustituye sus contenidos con un PNG o JPEG, actualiza la capa, y salva el PSD y un preview P NG.

// File: Program.cs
using System;
using System.IO;
using System.Linq;
using Aspose.PSD;
using Aspose.PSD.FileFormats.Psd;
using Aspose.PSD.FileFormats.Psd.Layers.SmartObjects;
using Aspose.PSD.ImageOptions;

class Program
{
    static void Main()
    {
        var inputPsd      = "template.psd";
        var replacement   = "replacement.png"; // any raster format supported by Aspose.PSD
        var outputPsd     = "output.psd";
        var outputPreview = "output-preview.png";

        if (!File.Exists(inputPsd) || !File.Exists(replacement))
        {
            Console.WriteLine("Missing input files.");
            return;
        }

        using (var psd = (PsdImage)Image.Load(inputPsd))
        {
            // Find the first smart object layer
            var smart = psd.Layers.OfType<SmartObjectLayer>().FirstOrDefault();
            if (smart == null)
            {
                Console.WriteLine("No smart object layer found in PSD.");
            }
            else
            {
                // Load the replacement raster and replace contents
                using var newContent = (RasterImage)Image.Load(replacement);

                // Replace embedded contents and update the smart object
                smart.ReplaceContents(newContent);
                smart.UpdateModifiedContent();
            }

            // Save updated PSD
            psd.Save(outputPsd);

            // Optional preview export
            psd.Save(outputPreview, new PngOptions());
        }

        Console.WriteLine("Done.");
    }
}

Notas

  • ReplaceContents sustituye el contenido incorporado del objeto inteligente.
  • UpdateModifiedContent refresca la capa de rendimiento después de la sustitución.
  • El ahorro de una previsión PNG te ayuda a validar el resultado sin abrir Photoshop.

Substituir un objeto inteligente por el nombre de la capa

Utilice este patrón cuando su plantilla tiene múltiples objetos inteligentes y desea dirigir a uno específico por nombre de pantalla.

using System.Linq;
using Aspose.PSD;
using Aspose.PSD.FileFormats.Psd;
using Aspose.PSD.FileFormats.Psd.Layers.SmartObjects;

static void ReplaceByName(string psdPath, string layerName, string replacementPath, string outputPsd)
{
    using var psd = (PsdImage)Image.Load(psdPath);

    var smart = psd.Layers
                   .OfType<SmartObjectLayer>()
                   .FirstOrDefault(l => string.Equals(l.DisplayName, layerName, StringComparison.OrdinalIgnoreCase));

    if (smart == null)
        throw new InvalidOperationException($"Smart object layer '{layerName}' not found.");

    using var newContent = (RasterImage)Image.Load(replacementPath);

    smart.ReplaceContents(newContent);
    smart.UpdateModifiedContent();

    psd.Save(outputPsd);
}

Lo llamo así:

ReplaceByName("template.psd", "Product Image", "new-photo.jpg", "output.psd");

Substituir todos los objetos inteligentes en un PSD

Este ejemplo fluye a través de todas las capas de objetos inteligentes y reemplaza cada una con la misma imagen.

using System.Linq;
using Aspose.PSD;
using Aspose.PSD.FileFormats.Psd;
using Aspose.PSD.FileFormats.Psd.Layers.SmartObjects;

static void ReplaceAll(string psdPath, string replacementPath, string outputPsd)
{
    using var psd = (PsdImage)Image.Load(psdPath);
    using var newContent = (RasterImage)Image.Load(replacementPath);

    var smartLayers = psd.Layers.OfType<SmartObjectLayer>().ToList();
    if (smartLayers.Count == 0)
        throw new InvalidOperationException("No smart object layers found.");

    foreach (var smart in smartLayers)
    {
        smart.ReplaceContents(newContent);
        smart.UpdateModifiedContent();
    }

    psd.Save(outputPsd);
}

Tratar objetos inteligentes conectados

Si un objeto inteligente está vinculado a un archivo externo, puede reemplazar el objetivo de enlace señalándolo a una nueva imagen en el disco. UpdateModifiedContent.

using System.Linq;
using Aspose.PSD;
using Aspose.PSD.FileFormats.Psd;
using Aspose.PSD.FileFormats.Psd.Layers.SmartObjects;

static void ReplaceLinked(string psdPath, string newLinkedFilePath, string outputPsd)
{
    using var psd = (PsdImage)Image.Load(psdPath);

    var linked = psd.Layers
                    .OfType<SmartObjectLayer>()
                    .FirstOrDefault(l => l.IsLinked);

    if (linked == null)
        throw new InvalidOperationException("No linked smart object layer found.");

    // Point the layer to a new external file
    linked.SetLinkedFile(newLinkedFilePath);

    // Refresh layer rendering
    linked.UpdateModifiedContent();

    psd.Save(outputPsd);
}

Notas

  • Uso IsLinked Detectar objetos inteligentes conectados.
  • SetLinkedFile actualiza el camino externo utilizado por la capa.
  • El archivo vinculado debe ser un formato de raster apoyado.

Las mejores prácticas

  • Dimensiones de imagen: Para la mejor calidad, se ajusta la relación y resolución del aspecto de la imagen de reemplazo a los límites de objetos inteligentes originales.
  • Gestión de colores: Mantener los perfiles de color consistentes a través de los modelos y los activos de reemplazo.
  • Batch automation: Reutilizar una carga RasterImage Cuando se sustituyen varias capas para reducir el I/O y la memoria.
  • Validación: Exporta una previsión de PNG después de la sustitución para confirmar la alineación y la escalación antes de distribuir los PSD.
  • Fallbacks: Si un documento no tiene objetos inteligentes, fracasar rápidamente con un error claro o romper el archivo en modo de batch.

Con estos patrones se pueden construir tubos de modelo de PSD fiables que sustituyen objetos inteligentes a escala y almacenan accesorios actualizados sin abrir Photoshop.

More in this category