Cambia lo sfondo in GIFs tramite C#
Crea le tue app .NET per cambiare lo sfondo nei file GIF utilizzando le API lato server.
Come cambiare lo sfondo nei file GIF usando C#
Spesso, per ottenere l’immagine ideale è necessario modificare lo sfondo. Per ottenere l’effetto immagine desiderato nel formato GIF, gli oggetti in primo piano devono essere isolati dal resto dell’immagine. Il rilevamento automatico degli oggetti è possibile se lo sfondo è uniforme. Se lo sfondo della foto non è uniforme o la separazione degli oggetti è difficile, si consiglia di premarcare l’immagine. Ciò comporta l’identificazione delle regioni rettangolari all’interno della foto in cui risiedono gli oggetti desiderati e la specificazione dei loro tipi. Questa operazione può essere eseguita manualmente o automaticamente tramite la funzionalità di riconoscimento degli oggetti dell’API Cloud. Dopo la selezione dell’oggetto e la rimozione dello sfondo originale, è possibile applicare un nuovo sfondo o implementare la trasparenza. Per cambiare lo sfondo nei file GIF, utilizzeremo Aspose.Imaging per .NET API che è un’API di conversione e manipolazione delle immagini ricca di funzionalità, potente e facile da usare per la piattaforma C#. Aprire NuGet gestore pacchetti, cerca Aspose.Imaging e installa. È inoltre possibile utilizzare il seguente comando dalla Console di gestione pacchetti.
Comando della console di Package Manager
PM> Install-Package Aspose.Imaging
Passaggi per cambiare lo sfondo in GIFs tramite C#
Hai bisogno del aspose.imaging.dll per provare il seguente flusso di lavoro nel tuo ambiente.
- Carica file GIF con il metodo Image.Load
- Cambia sfondo;
- Salva l’immagine su disco nel formato supportato da Aspose.Imaging
Requisiti di sistema
Aspose.Imaging per .NET è supportato su tutti i principali sistemi operativi. Assicurati solo di avere i seguenti prerequisiti.
- Microsoft Windows o un sistema operativo compatibile con .NET Framework, .NET Core, applicazione Windows, applicazione Web ASP.NET.
- Ambiente di sviluppo come Microsoft Visual Studio.
- Aspose.Imaging per .NET referenziato nel progetto.
Cambia lo sfondo nelle immagini GIF - .NET
using Aspose.Imaging; | |
using Aspose.Imaging.FileFormats.Emf; | |
using Aspose.Imaging.FileFormats.Png; | |
using Aspose.Imaging.FileFormats.Tiff.Enums; | |
using Aspose.Imaging.ImageOptions; | |
using Aspose.Imaging.Masking; | |
using Aspose.Imaging.Masking.Options; | |
using Aspose.Imaging.Masking.Result; | |
using Aspose.Imaging.Sources; | |
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
string templatesFolder = @"c:\Users\USER\Downloads"; | |
RemoveBackgroundGenericExample(); | |
void RemoveBackgroundProcessingWithManualRectangles() | |
{ | |
List<string> rasterFormats = new List<string>() { "jpg", "png", "bmp", "apng", "dicom", | |
"jp2", "j2k", "tga", "webp", "tif", "gif","ico" }; | |
List<string> vectorFormats = new List<string>() { "svg", "otg", "odg", "wmf", "emf", "wmz", "emz", "cmx", "cdr" }; | |
List<string> allFormats = new List<string>(rasterFormats); | |
allFormats.AddRange(vectorFormats); | |
allFormats.ForEach( | |
formatExt => | |
{ | |
var inputFile = Path.Combine(templatesFolder, $"couple.{formatExt}"); | |
bool isVectorFormat = vectorFormats.IndexOf(formatExt) > -1; | |
//Need to rasterize vector formats before background remove | |
if (isVectorFormat) | |
{ | |
inputFile = RasterizeVectorImage(formatExt, inputFile); | |
} | |
var outputFile = Path.Combine(templatesFolder, $"remove_background_manual_rectangles.{formatExt}"); | |
Console.WriteLine($"Processing {formatExt}"); | |
using (var image = (RasterImage)Image.Load(inputFile)) | |
{ | |
//Additional code examples can be found at | |
//https://docs.aspose.com/imaging/net/remove-background-from-images/#graph-cut-auto-masking-using-imagingcloud-api | |
var maskingOptions = new AutoMaskingGraphCutOptions | |
{ | |
FeatheringRadius = 2, | |
Method = SegmentationMethod.GraphCut, | |
Args = new AutoMaskingArgs() | |
{ | |
ObjectsRectangles = new Aspose.Imaging.Rectangle[] | |
{ | |
// girl's bound box | |
new Aspose.Imaging.Rectangle(87, 47, 123, 308), | |
// boy's bound box | |
new Aspose.Imaging.Rectangle(180, 24, 126, 224) | |
} | |
}, | |
ExportOptions = new PngOptions | |
{ | |
ColorType = PngColorType.TruecolorWithAlpha, | |
Source = new FileCreateSource(outputFile, false) | |
} | |
}; | |
using (var maskingSession = new ImageMasking(image).CreateSession(maskingOptions)) | |
{ | |
// first run of segmentation | |
using (maskingSession.Decompose()) { } | |
var argsWithUserMarkers = new AutoMaskingArgs() | |
{ | |
ObjectsPoints = new Point[][] | |
{ | |
// background markers | |
null, | |
// foreground markers | |
new UserMarker() | |
// boy's head | |
.AddPoint(218, 48, 10) | |
// girl's head | |
.AddPoint(399, 66, 10) | |
// girs's body | |
.AddPoint(158, 141, 10) | |
.AddPoint(158, 209, 20) | |
.AddPoint(115, 225, 5) | |
.GetPoints() | |
} | |
}; | |
using (var maskingResult = maskingSession.ImproveDecomposition(argsWithUserMarkers)) | |
{ | |
using (var resultImage = maskingResult[1].GetImage()) | |
{ | |
resultImage.Save(); | |
} | |
} | |
} | |
} | |
File.Delete(outputFile); | |
//Remove rasterized vector image | |
if (isVectorFormat) | |
{ | |
File.Delete(inputFile); | |
} | |
} | |
); | |
} | |
void RemoveBackgroundAutoProcessingWithAssumedObjects() | |
{ | |
List<string> rasterFormats = new List<string>() { "jpg", "png", "bmp", "apng", "dicom", | |
"jp2", "j2k", "tga", "webp", "tif", "gif" }; | |
List<string> vectorFormats = new List<string>() { "svg", "otg", "odg", "eps", "wmf", "emf", "wmz", "emz", "cmx", "cdr" }; | |
List<string> allFormats = new List<string>(rasterFormats); | |
allFormats.AddRange(vectorFormats); | |
allFormats.ForEach( | |
formatExt => | |
{ | |
var inputFile = Path.Combine(templatesFolder, $"couple.{formatExt}"); | |
bool isVectorFormat = vectorFormats.IndexOf(formatExt) > -1; | |
//Need to rasterize vector formats before background remove | |
if (isVectorFormat) | |
{ | |
inputFile = RasterizeVectorImage(formatExt, inputFile); | |
} | |
var outputFile = Path.Combine(templatesFolder, $"remove_background_auto_assumed_objects.{formatExt}"); | |
Console.WriteLine($"Processing {formatExt}"); | |
using (var image = (RasterImage)Image.Load(inputFile)) | |
{ | |
//Additional code examples can be found at | |
//https://docs.aspose.com/imaging/net/remove-background-from-images/#graph-cut-auto-masking-using-imagingcloud-api | |
var maskingOptions = new AutoMaskingGraphCutOptions | |
{ | |
AssumedObjects = new List<AssumedObjectData> | |
{ | |
// girl's bound box | |
new AssumedObjectData(DetectedObjectType.Human, new Aspose.Imaging.Rectangle(87, 47, 123, 308)), | |
// boy's bound box | |
new AssumedObjectData(DetectedObjectType.Human, new Aspose.Imaging.Rectangle(180, 24, 126, 224)), | |
}, | |
CalculateDefaultStrokes = true, | |
FeatheringRadius = 1, | |
Method = SegmentationMethod.GraphCut, | |
ExportOptions = new PngOptions | |
{ | |
ColorType = PngColorType.TruecolorWithAlpha, | |
Source = new FileCreateSource(outputFile, false) | |
}, | |
BackgroundReplacementColor = Color.Green | |
}; | |
using (var maskingResult = new ImageMasking(image).Decompose(maskingOptions)) | |
{ | |
using (var resultImage = maskingResult[1].GetImage()) | |
{ | |
resultImage.Save(); | |
} | |
} | |
} | |
//Remove rasterized vector image | |
if (isVectorFormat) | |
{ | |
File.Delete(inputFile); | |
} | |
File.Delete(outputFile); | |
} | |
); | |
} | |
void RemoveBackgroundAutoProcessing() | |
{ | |
List<string> rasterFormats = new List<string>() { "jpg", "png", "bmp", "apng", "dicom", | |
"jp2", "j2k", "tga", "webp", "tif", "gif" }; | |
List<string> vectorFormats = new List<string>() { "svg", "otg", "odg", "eps", "wmf", "emf", "wmz", "emz", "cmx", "cdr" }; | |
List<string> allFormats = new List<string>(rasterFormats); | |
allFormats.AddRange(vectorFormats); | |
allFormats.ForEach( | |
formatExt => | |
{ | |
var inputFile = Path.Combine(templatesFolder, $"couple.{formatExt}"); | |
bool isVectorFormat = vectorFormats.IndexOf(formatExt) > -1; | |
//Need to rasterize vector formats before background remove | |
if (isVectorFormat) | |
{ | |
inputFile = RasterizeVectorImage(formatExt, inputFile); | |
} | |
var outputFile = Path.Combine(templatesFolder, $"remove_background_auto.{formatExt}"); | |
Console.WriteLine($"Processing {formatExt}"); | |
using (var image = (RasterImage)Image.Load(inputFile)) | |
{ | |
//Additional code examples can be found at | |
//https://docs.aspose.com/imaging/net/remove-background-from-images/#graph-cut-auto-masking-using-imagingcloud-api | |
var maskingOptions = new AutoMaskingGraphCutOptions | |
{ | |
FeatheringRadius = 1, | |
Method = SegmentationMethod.GraphCut, | |
ExportOptions = new PngOptions | |
{ | |
ColorType = PngColorType.TruecolorWithAlpha, | |
Source = new FileCreateSource(outputFile, false) | |
}, | |
BackgroundReplacementColor = Color.Green | |
}; | |
using (var maskingResult = new ImageMasking(image).Decompose(maskingOptions)) | |
{ | |
using (var resultImage = maskingResult[1].GetImage()) | |
{ | |
resultImage.Save(); | |
} | |
} | |
} | |
//Remove rasterized vector image | |
if (isVectorFormat) | |
{ | |
File.Delete(inputFile); | |
} | |
File.Delete(outputFile); | |
} | |
); | |
} | |
void RemoveBackgroundGenericExample() | |
{ | |
List<string> rasterFormats = new List<string>() { "jpg", "png", "bmp", "apng", "dicom", | |
"jp2", "j2k", "tga", "webp", "tif", "gif" }; | |
List<string> vectorFormats = new List<string>() { "svg", "otg", "odg", "wmf", "emf", "wmz", "emz", "cmx", "cdr" }; | |
List<string> allFormats = new List<string>(rasterFormats); | |
allFormats.AddRange(vectorFormats); | |
allFormats.ForEach( | |
formatExt => | |
{ | |
var inputFile = Path.Combine(templatesFolder, $"couple.{formatExt}"); | |
bool isVectorFormat = vectorFormats.IndexOf(formatExt) > -1; | |
//Need to rasterize vector formats before background remove | |
if (isVectorFormat) | |
{ | |
inputFile = RasterizeVectorImage(formatExt, inputFile); | |
} | |
var outputFile = Path.Combine(templatesFolder, $"remove_background.{formatExt}"); | |
Console.WriteLine($"Processing {formatExt}"); | |
using (var image = (RasterImage)Image.Load(inputFile)) | |
{ | |
//Additional code examples can be found at | |
//https://docs.aspose.com/imaging/net/remove-background-from-images/#graph-cut-auto-masking-using-imagingcloud-api | |
var maskingOptions = new AutoMaskingGraphCutOptions | |
{ | |
CalculateDefaultStrokes = true, | |
FeatheringRadius = 1, | |
Method = SegmentationMethod.GraphCut, | |
ExportOptions = new PngOptions | |
{ | |
ColorType = PngColorType.TruecolorWithAlpha, | |
Source = new FileCreateSource(outputFile, false) | |
}, | |
BackgroundReplacementColor = Color.Green | |
}; | |
using (var maskingResult = new ImageMasking(image).Decompose(maskingOptions)) | |
{ | |
using (var resultImage = maskingResult[1].GetImage()) | |
{ | |
resultImage.Save(); | |
} | |
} | |
} | |
//Remove rasterized vector image | |
if (isVectorFormat) | |
{ | |
File.Delete(inputFile); | |
} | |
File.Delete(outputFile); | |
} | |
); | |
} | |
string RasterizeVectorImage(string formatExt, string inputFile) | |
{ | |
string outputFile = Path.Combine(templatesFolder, $"rasterized.{formatExt}.png"); | |
using (var image = Image.Load(inputFile)) | |
{ | |
image.Save(outputFile, new PngOptions()); | |
} | |
return outputFile; | |
} | |
class UserMarker | |
{ | |
private readonly List<Point> _list = new List<Point>(); | |
public UserMarker AddPoint(int left, int top, int radius) | |
{ | |
for (var y = top - radius; y <= top + radius; y++) | |
{ | |
for (var x = left - radius; x <= left + radius; x++) | |
{ | |
this._list.Add(new Point(x, y)); | |
} | |
} | |
return this; | |
} | |
public Point[] GetPoints() | |
{ | |
return this._list.ToArray(); | |
} | |
} |
Informazioni su Aspose.Imaging per l'API .NET
Aspose.Imaging API è una soluzione di elaborazione delle immagini per creare, modificare, disegnare o convertire immagini (foto) all’interno delle applicazioni. Offre: elaborazione delle immagini multipiattaforma, incluse, a titolo esemplificativo ma non esaustivo, conversioni tra vari formati di immagine (inclusa elaborazione uniforme di immagini multipagina o multiframe), modifiche come disegnare, lavorare con primitive grafiche, trasformazioni (ridimensiona, ritaglia, capovolgi e ruota , binarizzazione, scala di grigi, regolazione), funzionalità avanzate di manipolazione delle immagini (filtro, dithering, mascheratura, raddrizzatura) e strategie di ottimizzazione della memoria. È una libreria autonoma e non dipende da alcun software per le operazioni sulle immagini. È possibile aggiungere facilmente funzionalità di conversione delle immagini ad alte prestazioni con API native all’interno dei progetti. Si tratta di API locali private al 100% e le immagini vengono elaborate sui tuoi server.Cambia lo sfondo in GIFs tramite l’app online
Cambia lo sfondo nei documenti GIF visitando il nostro sito web demo live . La demo dal vivo ha i seguenti vantaggi
GIF Cos'è GIF Formato del file
Un formato GIF o Graphical Interchange Format è un tipo di immagine altamente compressa. Di proprietà di Unisys, GIF utilizza l'algoritmo di compressione LZW che non degrada la qualità dell'immagine. Per ogni immagine GIF in genere consentono fino a 8 bit per pixel e sono consentiti fino a 256 colori nell'immagine. In contrasto con un'immagine JPEG, che può visualizzare fino a 16 milioni di colori e tocca abbastanza i limiti dell'occhio umano. Quando è emerso Internet, le GIF sono rimaste la scelta migliore perché richiedevano una larghezza di banda ridotta e compatibili per la grafica che consuma aree di colore solide. Una GIF animata combina numerose immagini o fotogrammi in un unico file e le visualizza in sequenza per generare una clip animata o un breve video. I limiti di colore sono fino a 256 per ogni fotogramma e sono probabilmente i meno adatti per riprodurre altre immagini e fotografie con gradiente di colore.
Per saperne di piùAltri formati supportati Cambia sfondo
Usando C#, si può facilmente cambiare lo sfondo in diversi formati tra cui.