Automatização de substituição de objetos inteligentes ajuda a criar variações do mesmo modelo de Photoshop com imagens diferentes. com Aspose.PSD para .NET você pode carregar um PSD, localizar camadas de objeto inteligente, substituir seus conteúdos incorporados com uma nova imagem, e salvar o documento atualizado.
Pré-requisitos
- .NET 6 ou posterior
- Nuvem em:
Aspose.PSD
dotnet add package Aspose.PSD
Substituir o primeiro objeto inteligente em um PSD
Este exemplo carrega um PSD, encontra o primeiro SmartObjectLayer
, substitui os seus conteúdos por um PNG ou JPEG, atualiza a camada e salva o PSD e um pré-visualização de 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.");
}
}
Notas
ReplaceContents
substitui o conteúdo incorporado do objeto inteligente.UpdateModifiedContent
Refrigerar a camada de renderização após a substituição.- Salvar uma previsão PNG ajuda você a validar o resultado sem abrir o Photoshop.
Substituir um objeto inteligente por um nome de camada
Use este padrão quando o seu modelo tem vários objetos inteligentes e você quer direcionar um específico por nome de exibição.
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);
}
Chamamos isso assim:
ReplaceByName("template.psd", "Product Image", "new-photo.jpg", "output.psd");
Substituir todos os objetos inteligentes em um PSD
Este exemplo passa por todas as camadas de objetos inteligentes e substitui cada uma com a mesma imagem.
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);
}
Tratamento de objetos inteligentes ligados
Se um objeto inteligente estiver ligado a um arquivo externo, você pode substituir o objetivo do link indicando-o para uma nova imagem no 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
- Utilização
IsLinked
Detecção de objetos inteligentes ligados. SetLinkedFile
atualizar o caminho externo utilizado pela camada.- O arquivo ligado deve ser um formato de raster suportado.
Melhores práticas
- Grandes de imagem: Para a melhor qualidade, corresponde o aspecto da imagem de substituição e a resolução aos limites do objeto inteligente original.
- Gestão de cores: Mantenha os perfis de cor consistentes em templates e ativos de substituição.
- Automatização de batch: Reutilizar um carregado
RasterImage
quando substituir várias camadas para reduzir o I/O e a memória. - Validação: Exporta uma previsão PNG após a substituição para confirmar a alinhamento e a escalação antes da distribuição de PSDs.
- Fallbacks: Se um documento não tem objetos inteligentes, falhar rapidamente com um erro claro ou desligar o arquivo em modo de batch.
Com esses padrões, você pode construir tubos de padrão PSD confiáveis que substituem objetos inteligentes em escala e salvem entregas atualizadas sem abrir o Photoshop.