Automatizzare la sostituzione degli oggetti intelligenti ti aiuta a creare variazioni dello stesso modello di Photoshop con immagini diverse. Aspose.PSD per .NET puoi caricare un PSD, localizzare le strati di oggetto intelligente, sostituire i loro contenuti incorporati con una nuova immagine e salvare il documento aggiornato.

Prerequisiti

  • .NET 6 o successivo
  • di NuGet: Aspose.PSD
dotnet add package Aspose.PSD

sostituire il primo oggetto intelligente in un PSD

Questo esempio carica un PSD, trova il primo SmartObjectLayer, sostituisce il suo contenuto con un PNG o JPEG, aggiornare la striscia e salvare il PSD e una preview Png.

// 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.");
    }
}

Notizie

  • ReplaceContents sostituisce il contenuto incorporato dell’oggetto intelligente.
  • UpdateModifiedContent Ristrutturare la striscia dopo la sostituzione.
  • Il risparmio di una preview PNG ti aiuta a valutare il risultato senza aprire Photoshop.

Sostituisci un oggetto intelligente con un nome di strato

Utilizzare questo modello quando il tuo modello ha più oggetti intelligenti e si desidera mirare uno specifico con il nome di visualizzazione.

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);
}

Chiamalo così:

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

Sostituisci tutti gli oggetti intelligenti in un PSD

Questo esempio scorre attraverso tutte le strati di oggetti intelligenti e sostituisce ciascuno con la stessa immagine.

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);
}

Trattamento di oggetti intelligenti collegati

Se un oggetto intelligente è collegato a un file esterno, puoi sostituire il target di collegamento indicandolo a una nuova immagine sul 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);
}

Notizie

  • Utilizzo IsLinked per rilevare oggetti intelligenti collegati.
  • SetLinkedFile aggiornare il percorso esterno utilizzato dalla striscia.
  • Il file collegato deve essere un formato raster supportato.

Le migliori pratiche

  • ** Dimensioni di immagine**: Per la migliore qualità, corrisponde il rapporto di aspetto e la risoluzione dell’immagine sostitutiva ai limiti degli oggetti intelligenti originali.
  • Gestione dei colori: Mantenere i profili colorati coerenti tra i modelli e gli attivi di sostituzione.
  • Batch automation: riutilizzo di un carico RasterImage quando sostituisce molte strati per ridurre I/O e la memoria.
  • Validazione: esportare una preview PNG dopo la sostituzione per confermare l’allineamento e la scalazione prima della distribuzione dei PSD.
  • Fallbacks: Se un documento non ha oggetti intelligenti, fallisce rapidamente con un errore chiaro o scioglie il file in modalità batch.

Con questi modelli puoi costruire pipeline di modello PSD affidabili che sostituiscono oggetti intelligenti a scala e salvare livelli aggiornati senza aprire Photoshop.

More in this category