C#을 통한 이미지 파일 변환

이미지 형식, 메타파일, WebP, Svg, Apng를 변환하여 플랫폼 간 .NET 기반 고급 이미지 처리 응용 프로그램을 구축합니다.

 

.NET Image API는 프로그래머를 위한 고급 이미지 처리 및 렌더링 기능을 용이하게 합니다. 개발자는 이를 통합하여 사진과 그림을 포함한 래스터 및 벡터 이미지를 PSD, PDF, GIF, PNG, DICOM, SVG, JPG, JPEG2000, APNG, BMP, TIFF, HTML5 CANVAS, WEBP, WMF, EMF 및 기타 이미지 형식으로 변환할 수 있습니다. . API는 파일 변환을 처리할 뿐만 아니라 이미지를 흑백 및 회색조로 변환하고 GIF 이미지 레이어를 변환하는 등의 작업을 처리합니다.

이미지를 비트맵 BMP, JPG, PNG로 변환

C# Image API를 사용하면 원하는 형식의 확장자를 변경하는 것만으로 Inter 형식 변환이 쉽습니다. 다음은 image to bmp, image to jpg, image to png와 같은 몇 가지 일반적인 경우이며 개발자는 특정 형식에 맞게 쉽게 향상할 수 있습니다. Image.Load 를 통해 소스 이미지를 로드하는 과정입니다. 특정 설정에 대한 대상 이미지 형식 옵션 의 개체를 만듭니다. 마지막으로 경로 및 저장 옵션을 매개변수로 대상 파일을 전달하여 저장 방법 을 호출합니다.

이미지의 상호 변환을 위한 C# 코드

using Aspose.Imaging;
using Aspose.Imaging.FileFormats.Png;
using Aspose.Imaging.ImageOptions;
using System.Collections.Generic;
using System.IO;
using System.Linq;
string templatesFolder = @"c:\Users\USER\Downloads\templates\";
string dataDir = templatesFolder;
ProcessConvertion();
void ProcessConvertion()
{
//Get list of supported formats in
//Aspose.Imaging for loading and saving images
var formats = GetAvailableImageFormats();
var importFormats = formats.Import;
var exportFormats = formats.Export;
//Process each raster and vector format that can be loaded
foreach (var format in importFormats)
{
string formatExt = format.Key;
var inputFile = Path.Combine(templatesFolder, $"template.{formatExt}");
//Process each raster and vector format
//to which we can save imported image
foreach (var exportFormat in exportFormats)
{
var outputFile = Path.Combine(templatesFolder, $"convert-{formatExt}-to-{exportFormat.Key}.{exportFormat.Key}");
System.Console.WriteLine("Processing conversion:" + outputFile);
//More about load method can be found at
//https://apireference.aspose.com/imaging/net/aspose.imaging.image/load/methods/2
//Load imported image
using (var image = Image.Load(inputFile))
{
//Obtain default saving options defined for each image
ImageOptionsBase exportOptions = exportFormat.Value.Clone();
//If loaded image is vector, need to specify vector rasterization options
//for export to another vector
if (image is VectorImage)
{
VectorRasterizationOptions rasterizationOptions = format.Value;
rasterizationOptions.PageWidth = image.Width;
rasterizationOptions.PageHeight = image.Height;
exportOptions.VectorRasterizationOptions = rasterizationOptions;
}
image.Save(outputFile, exportOptions);
}
File.Delete(outputFile);
}
//System.GC.Collect();
}
}
(Dictionary<string, VectorRasterizationOptions> Import, Dictionary<string, ImageOptionsBase> Export) GetAvailableImageFormats()
{
////////////////////////////////
///Raster and vector formats to that we can export images
////////////////////////////////
//Raster image formats that support both - save and load and their default save options
Dictionary<string, ImageOptionsBase> rasterFormatsThatSupportExportAndImport = new Dictionary<string, ImageOptionsBase>()
{
{ "bmp", new BmpOptions()},
{ "gif", new GifOptions()},
{ "dicom", new DicomOptions()},
{ "jpg", new JpegOptions()},
{ "jpeg", new JpegOptions()},
{ "jpeg2000", new Jpeg2000Options() },
{ "j2k", new Jpeg2000Options { Codec = Aspose.Imaging.FileFormats.Jpeg2000.Jpeg2000Codec.J2K } },
{ "jp2", new Jpeg2000Options { Codec = Aspose.Imaging.FileFormats.Jpeg2000.Jpeg2000Codec.Jp2 }},
{ "png",new PngOptions(){ ColorType = PngColorType.TruecolorWithAlpha} },
{ "apng", new ApngOptions()},
{ "tiff", new Aspose.Imaging.ImageOptions.TiffOptions(Aspose.Imaging.FileFormats.Tiff.Enums.TiffExpectedFormat.Default)},
{ "tif", new Aspose.Imaging.ImageOptions.TiffOptions(Aspose.Imaging.FileFormats.Tiff.Enums.TiffExpectedFormat.Default)},
{ "tga", new TgaOptions()},
{ "webp", new WebPOptions()},
{ "ico", new IcoOptions()}
};
//Vector image formats that support both - save and load, their default save options
//and their rasterization options when exporting to another vector image
Dictionary<string, (ImageOptionsBase, VectorRasterizationOptions)> vectorFormatsThatSupportExportAndImport
= new Dictionary<string, (ImageOptionsBase, VectorRasterizationOptions)>()
{
{ "emf", (new EmfOptions(),new EmfRasterizationOptions()) },
{ "svg", (new SvgOptions(), new SvgRasterizationOptions())},
{ "wmf", (new WmfOptions(), new WmfRasterizationOptions())},
{ "emz", (new Aspose.Imaging.ImageOptions.EmfOptions(){ Compress = true }, new EmfRasterizationOptions())},
{ "wmz", (new Aspose.Imaging.ImageOptions.WmfOptions(){ Compress = true }, new WmfRasterizationOptions())},
{ "svgz", (new Aspose.Imaging.ImageOptions.SvgOptions(){ Compress = true }, new SvgRasterizationOptions())},
};
////////////////////////////////
///Raster and vector formats from which we can load images
////////////////////////////////
//Formats that can be only saved (supported only save to this formats)
Dictionary<string, ImageOptionsBase> formatsOnlyForExport = new Dictionary<string, ImageOptionsBase>()
{
{ "psd", new PsdOptions()},
{ "dxf", new DxfOptions(){ TextAsLines = true,ConvertTextBeziers = true} },
{ "pdf", new PdfOptions()},
{ "html", new Html5CanvasOptions()},
};
//Raster formats that can be only loaded
List<string> formatsOnlyForImport = new List<string>()
{
"djvu", "dng", "dib"
};
//Vector formats only for loading and their rasterization options when exporting to another vector format
Dictionary<string, VectorRasterizationOptions> vectorFormatsOnlyForImport = new Dictionary<string, VectorRasterizationOptions>()
{
{"eps", new EpsRasterizationOptions()},
{"cdr", new CdrRasterizationOptions() },
{"cmx", new CmxRasterizationOptions() },
{"otg", new OtgRasterizationOptions() },
{"odg", new OdgRasterizationOptions() }
};
//Get total set of formats to what we can export images
Dictionary<string, ImageOptionsBase> exportFormats = vectorFormatsThatSupportExportAndImport
.ToDictionary(s => s.Key, s => s.Value.Item1)
.Union(formatsOnlyForExport)
.Concat(rasterFormatsThatSupportExportAndImport)
.ToDictionary(s => s.Key, s => s.Value);
//Get total set of formats that can be loaded
Dictionary<string, VectorRasterizationOptions> importFormats = vectorFormatsOnlyForImport
.Union(formatsOnlyForImport.ToDictionary(s => s, s => new VectorRasterizationOptions()))
.Union(vectorFormatsThatSupportExportAndImport.ToDictionary(s => s.Key, s => s.Value.Item2))
.ToDictionary(s => s.Key, s => s.Value);
return (Import: importFormats, Export: exportFormats);
}

래스터 이미지를 PDF로 변환

래스터 이미지를 PDF로 변환하는 프로세스는 API가 특정 PDF 설정에 대해 PdfOptions 를 제공한다는 점을 제외하고 이미지 상호 변환과 동일합니다. . 프로그래머는 특정 요구 사항에 맞게 쉽게 향상시킬 수 있습니다.

래스터 이미지를 PDF로 변환하는 코드

using (Image imge = Image.Load(dataDir+ "transparent_orig.gif"))
{
imge.Save(dataDir+"output.pdf", new PdfOptions() { PdfDocumentInfo = new Aspose.Imaging.FileFormats.Pdf.PdfDocumentInfo() } );
}

SVG를 래스터 이미지 BMP, PNG, JPG로 변환

SVG의 변환 과정은 동일하며 SVG 파일을 로드하고 관련 이미지 저장 옵션을 사용하고 Save 메소드를 호출합니다. Image API는 PageWidth, PageHeight 및 래스터 이미지를 설정하기 위해 SvgRasterizationOptions 를 제공하며, 래스터 이미지는 초기화 및 SvgRasterizationOptions 옵션 가져오기를 위해 VectorRasterizationOptions 속성을 사용합니다.

SVG를 래스터 이미지로 변환하는 C# 코드

// Load the image
using (SvgImage image = (SvgImage)Image.Load(dataDir + "sourceFile.Svg"))
{
// Create an instance of relevant raster image options and Save the results to disk
PngOptions pngOptions = new PngOptions();
SvgRasterizationOptions svgOptions = new SvgRasterizationOptions();
svgOptions.PageWidth = 100;
svgOptions.PageHeight = 200;
pngOptions.VectorRasterizationOptions = svgOptions;
image.Save(dataDir + "ConvertingSVGToRasterImages_out.png", pngOptions);
}

변환할 이미지 지원되는 모든 형식

다음은 변환할 수 있는 이미지 형식의 전체 목록입니다.


변환할 지원되는 모든 이미지 형식

다음은 변환할 수 있는 이미지 형식의 전체 목록입니다.