
无论您是在构建网站、桌面应用程序还是移动应用程序,在处理和编辑图像时,对图像进行操作和绘制的能力都是一个至关重要的方面。为了让开发人员能够使用先进而又易于实现的绘图功能,我们推出了 Aspose.Imaging.Drawing,这是一个专为 C# .NET 应用程序设计的强大 API,可提供一系列图像绘图功能。
C# .NET 绘图 API
使用.NET绘图库创建图形
在 C# 中绘制图像
在 C# 中绘制矢量图像
为图像添加遮罩
手动图像屏蔽
自动图像屏蔽
对图像应用滤镜
裁剪、旋转和调整图像大小
将图像转换为其他格式
C# .NET 绘图库
Aspose.Imaging.Drawing 是一个强大的应用程序接口(API),可让您使用先进的图像处理技术处理光栅和矢量图像。通过本地字节访问,该 API 可确保在创建或处理图像时的高速处理。使用该 API,您可以通过像素操作和图形路径绘制对象,并将图像从一种格式转换为另一种格式。Aspose.Imaging.Drawing 使用 Aspose.Drawing 作为默认图形引擎,它是一个跨平台的 2D 图形库,可提供一整套绘制文本、几何图形和图像的功能,而无需任何外部依赖。
您可以从 NuGet 下载并安装 Aspose.Imaging.Drawing。
PM> NuGet\Install-Package Aspose.Imaging.Drawing
现在,让我们借助源代码来看看这个 .NET 绘图 API 的一些突出功能及其使用方法。
使用 .NET 绘图库创建图形
Aspose.Imaging.Drawing允许您通过绘制圆形、直线、三角形、正方形和椭圆形等不同对象来创建图像。不仅是光栅图像,您还可以使用 API 生成矢量图像。让我们来看看如何使用此 .NET 绘图 API 在 C# 中绘制光栅和矢量图像。
绘制光栅图像
以下是使用 Aspose.Imaging.Drawing API 绘制光栅图像的步骤。
首先,使用 Image.Create() 方法创建所需格式的图像。
然后,创建一个图形类对象,并用上面创建的图像对其进行初始化。
使用 Graphics.Clear 方法清除图像表面。
创建一支新笔,并用所需的颜色对其进行初始化。
使用 Graphics.DrawEllipse() 方法绘制椭圆(或其他图形对象)。
使用 Graphics.FillPolygon() 方法绘制多边形。
最后,使用 Image.Save() 方法保存图像。
以下代码片段展示了如何在 C# 中绘制图像。
string outputFolder = @"Output\";
// Create an instance of BmpOptions and set its various properties
BmpOptions imageOptions = new BmpOptions();
imageOptions.BitsPerPixel = 24;
// Create an instance of FileCreateSource and assign it to Source property
imageOptions.Source = new FileCreateSource(outputFolder + "result.bmp", false);
using (var image = Image.Create(imageOptions, 500, 500))
{
var graphics = new Graphics(image);
// Clear the image surface with white color and Create and initialize a Pen object with blue color
graphics.Clear(Color.White);
var pen = new Pen(Color.Blue);
// Draw Ellipse by defining the bounding rectangle of width 150 and height 100 also Draw a polygon using the LinearGradientBrush
graphics.DrawEllipse(pen, new Rectangle(10, 10, 150, 100));
using (var linearGradientBrush = new LinearGradientBrush(image.Bounds, Color.Red, Color.White, 45f))
{
graphics.FillPolygon(linearGradientBrush, new[] { new Point(200, 200), new Point(400, 200), new Point(250, 350) });
}
// Save image
image.Save();
}绘制矢量图像
与光栅图像类似,您也可以通过几个简单的步骤绘制 SVG 等矢量图形。让我们使用 C# 绘图库创建一个矢量图像。
首先,创建一个 MemoryStream 对象。
然后,加载 SVG 图像。
将 SVG 栅格化为 PNG 并将结果写入流。
从流中加载 PNG 图像,以便进一步绘制。
在现有的 SVG 图像上绘制 PNG 图像。
最后保存结果。
以下代码片段展示了如何用 C# 绘制矢量图像。
string templatesFolder = @"Templates\";
string outputFolder = @"Output\";
using (MemoryStream drawnImageStream = new MemoryStream())
{
// First, rasterize Svg to Png and write the result to a stream.
using (SvgImage svgImage = (SvgImage)Image.Load(templatesFolder + "template.svg"))
{
SvgRasterizationOptions rasterizationOptions = new SvgRasterizationOptions();
rasterizationOptions.PageSize = svgImage.Size;
PngOptions saveOptions = new PngOptions();
saveOptions.VectorRasterizationOptions = rasterizationOptions;
svgImage.Save(drawnImageStream, saveOptions);
// Now load a Png image from stream for further drawing.
drawnImageStream.Seek(0, System.IO.SeekOrigin.Begin);
using (RasterImage imageToDraw = (RasterImage)Image.Load(drawnImageStream))
{
// Drawing on the existing Svg image.
Aspose.Imaging.FileFormats.Svg.Graphics.SvgGraphics2D graphics = new Aspose.Imaging.FileFormats.Svg.Graphics.SvgGraphics2D(svgImage);
// Scale down the entire drawn image by 2 times and draw it to the center of the drawing surface.
int width = imageToDraw.Width / 2;
int height = imageToDraw.Height / 2;
Point origin = new Point((svgImage.Width - width) / 2, (svgImage.Height - height) / 2);
Size size = new Size(width, height);
graphics.DrawImage(imageToDraw, origin, size);
// Save the result image
using (SvgImage resultImage = graphics.EndRecording())
{
resultImage.Save(outputFolder + "vector_image.svg");
}
}
}
}为图像添加遮罩
图像编辑中的遮罩是指有选择地隐藏或显示图像某些部分的技术。它需要创建一个遮罩,遮罩本质上是一个灰度图像,它定义了原始图像中每个像素的透明度或不透明度。图像遮罩被广泛用于识别和诊断。
Aspose.Image.Drawing 提供了两种应用图像遮罩的方法:
手动遮罩--它使用一组 ROI 作为遮罩。每个切片的 ROI 都用于定义遮罩。它需要额外的用户输入。
自动屏蔽 - 它不需要用户输入大量数据,但可能不太准确。
现在让我们看看如何在 C# 代码中对图像应用手动和自动掩膜。
手动图像屏蔽
以下代码片段展示了如何在 C# 代码中对图像应用手动屏蔽。
string outputFolder = @"Output\";
// Source file
string sourceFileName = outputFolder + "couple.png";
// Create graphics path
GraphicsPath manualMask = new GraphicsPath();
// Add shapes
Figure firstFigure = new Figure();
firstFigure.AddShape(new EllipseShape(new RectangleF(100, 30, 40, 40)));
firstFigure.AddShape(new RectangleShape(new RectangleF(10, 200, 50, 30)));
// Add figure
manualMask.AddFigure(firstFigure);
GraphicsPath subPath = new GraphicsPath();
Figure secondFigure = new Figure();
secondFigure.AddShape(
new PolygonShape(
new PointF[]
{
new PointF(310, 100), new PointF(350, 200), new PointF(250, 200)
}, true));
secondFigure.AddShape(new PieShape(new RectangleF(10, 10, 80, 80), 30, 120));
subPath.AddFigure(secondFigure);
manualMask.AddPath(subPath);
// Apply masking
using (RasterImage image = (RasterImage)Image.Load(sourceFileName))
{
MaskingOptions maskingOptions = new MaskingOptions()
{
Method = SegmentationMethod.Manual,
Args = new ManualMaskingArgs
{
Mask = manualMask
},
Decompose = false,
ExportOptions =
new PngOptions()
{
ColorType = PngColorType.TruecolorWithAlpha,
Source = new StreamSource(new MemoryStream())
},
};
MaskingResult results = new ImageMasking(image).Decompose(maskingOptions);
// Saving final masking result.
using (RasterImage resultImage = (RasterImage)results[1].GetImage())
{
resultImage.Save(outputFolder + "manual_masking.png", new PngOptions() { ColorType = PngColorType.TruecolorWithAlpha });
}
}自动图像屏蔽
下面的代码片段使用 .NET 绘图 API 对图像进行自动屏蔽。
string outputFolder = @"Output\";
MaskingResult results;
using (RasterImage image = (RasterImage)Image.Load(outputFolder + "couple.jpg"))
{
// To use Graph Cut with auto calculated strokes, AutoMaskingGraphCutOptions is used.
AutoMaskingGraphCutOptions options = new AutoMaskingGraphCutOptions
{
// Indicating that a new calculation of the default strokes should be performed during the image decomposition.
CalculateDefaultStrokes = true,
// Setting post-process feathering radius based on the image size.
FeatheringRadius = (Math.Max(image.Width, image.Height) / 500) + 1,
Method = SegmentationMethod.GraphCut,
Decompose = false,
ExportOptions =
new PngOptions()
{
ColorType = PngColorType.TruecolorWithAlpha,
Source = new FileCreateSource(outputFolder + "auto_masking.png")
},
BackgroundReplacementColor = Color.Transparent
};
results = new ImageMasking(image).Decompose(options);
using (RasterImage resultImage = (RasterImage)results[1].GetImage())
{
resultImage.Save(outputFolder + "auto_masking_2.png", new PngOptions() { ColorType = PngColorType.TruecolorWithAlpha });
}
}为图像应用滤镜
在图像中应用滤镜有多种用途,人们使用滤镜的原因也多种多样,既有实用性,也有艺术性。图像滤镜最常见的用途包括色彩校正、提高图像质量、应用特效、降噪等。Aspose.Imaging.Drawing 支持多种类型的滤镜,您可以将它们应用到图像中,例如中值滤镜、运动纬线滤镜、高斯纬线滤镜等。
下面的代码使用 Aspose.Imaging.Drawing 对图像应用了中值滤波器。
string templatesFolder = @"Templates\";
string outputFolder = @"Output\";
// Load the noisy image
using (Image image = Image.Load(templatesFolder + "template.gif"))
{
// Caste the image into RasterImage
RasterImage rasterImage = image as RasterImage;
if (rasterImage == null)
{
return;
}
// Create an instance of MedianFilterOptions class and set the size, Apply MedianFilterOptions filter to RasterImage object and Save the resultant image
MedianFilterOptions options = new MedianFilterOptions(4);
rasterImage.Filter(image.Bounds, options);
// Save image
image.Save(outputFolder + "median_filter.gif");
}裁剪、旋转和调整图像大小
裁剪、旋转和调整图像大小被认为是图像编辑应用程序的基本功能。它们是用于处理数字图像的最常见图像处理操作。让我们看看如何使用 Aspose.Imaging.Drawing API 来裁剪、旋转和调整图像大小。
裁剪图像
要裁剪图像,您需要提供图像四边的移动值。根据这些值,图像边界会向图像中心移动。以下 C# 代码片段将根据提供的移动值裁剪图像。
string templatesFolder = @"Templates\";
string outputFolder = @"Output\";
// Load an existing image into an instance of RasterImage class
using (RasterImage rasterImage = (RasterImage)Image.Load(templatesFolder + "template.jpg"))
{
// Before cropping, the image should be cached for better performance
if (!rasterImage.IsCached)
{
rasterImage.CacheData();
}
// Define shift values for all four sides
int leftShift = 10;
int rightShift = 10;
int topShift = 10;
int bottomShift = 10;
// Based on the shift values, apply the cropping on image Crop method will shift the image bounds toward the center of image and Save the results to disk
rasterImage.Crop(leftShift, rightShift, topShift, bottomShift);
// Save cropped image
rasterImage.Save(outputFolder + "cropped_image.jpg");
}旋转图像
要旋转图像,Aspose.Imaging.Drawing 提供了 RotateFlip 方法,该方法不仅能旋转图像,还能翻转图像(如果需要)。您可以从 RotateFlipType 枚举中选择所需的旋转和翻转选项。以下代码片段展示了如何在 C# 中旋转图像但不翻转图像。
string templatesFolder = @"Templates\";
string outputFolder = @"Output\";
// Loading and Rotating Image
using (var image = Image.Load(templatesFolder + "template.jpg"))
{
// Rotate image
image.RotateFlip(RotateFlipType.Rotate270FlipNone);
// Save image
image.Save(outputFolder + "rotated_image.jpg");
}调整图像大小
使用 Aspose.Imaging.Drawing 调整图像大小就像画饼一样简单。只需调用调整大小方法并传递新的高度和宽度值即可。以下代码片段展示了如何在 C# 中调整图像大小。
string templatesFolder = @"Templates\";
string outputFolder = @"Output\";
using (Image image = Image.Load(templatesFolder + "template.jpg"))
{
// Resize image
image.Resize(300, 300);
// Save image
image.Save(outputFolder + "resized_image.jpg");
}将图像转换为其他格式
使用 Aspose.Imaging.Drawing API 转换图像时,只需加载图像并将其保存为所需的输出格式即可。以下代码片段可将 JPG 图像转换为 WebP、PSD、PDF 和 TIFF 格式。
string templatesFolder = @"Templates\";
string outputFolder = @"Output\";
using (var img = Aspose.Imaging.Image.Load(templatesFolder + "template.jpg"))
{
// Save in different image formats
img.Save(outputFolder + "output.webp", new Aspose.Imaging.ImageOptions.WebPOptions());
img.Save(outputFolder + "output.psd ", new Aspose.Imaging.ImageOptions.PsdOptions());
img.Save(outputFolder + "output.tiff", new Aspose.Imaging.ImageOptions.TiffOptions(TiffExpectedFormat.Default));
// Save as PDF
PdfOptions exportOptions = new PdfOptions();
exportOptions.PdfDocumentInfo = new Aspose.Imaging.FileFormats.Pdf.PdfDocumentInfo();
img.Save(outputFolder + "output.pdf", exportOptions);
}获取免费 API 许可证
如果您想评估 Aspose.Imaging.Drawing API,可以获得免费的临时许可证,该许可证允许您不受任何限制地使用 API 的全部功能。
结论
在图形和图像处理领域,Aspose.Imaging.Drawing API 对于 C# .NET 开发人员来说是一个多功能的强大工具。无论您是要增强视觉元素、纠正图像失真还是在不同格式之间转换图像,该 API 都能提供一套全面的功能。有了 Aspose.Imaging.Drawing,图像处理触手可及,您可以通过编程创建引人注目、视觉效果极佳的图形。
渝公网安备50010702505508