此示例详细介绍了如何在 C# 中压缩 PNG。它涵盖了使用 C#** **压缩 PNG 的所有资源、命名空间、类、方法和工作示例代码。开发的应用程序可以在 Windows、Linux 或 macOS 内的任何 .NET 兼容环境中使用。
使用 C# 压缩 PNG 的步骤
- 使用 NuGet 包管理器添加 Aspose.Imaging 来建立环境
- 使用 Image 类的实例访问源 PNG 图像
- 使用 PngOptions 类设置压缩率和其他属性
- 将压缩的 PNG 图像保存在磁盘上
通过执行上述步骤,您可以使用分步方法在 C#* 中轻松管理 *PNG 压缩,我们通过在解决方案中包含所需资源来设置环境。然后,我们将使用 Image 类的实例从磁盘加载源 PNG 文件。在后续步骤中,将创建 PngOptions 类对象以设置压缩率和其他属性,然后将压缩后的 PNG 保存在磁盘上。
使用 C# 压缩 PNG 的代码
using Aspose.Imaging; | |
using Aspose.Imaging.FileFormats.Png; | |
using Aspose.Imaging.ImageOptions; | |
namespace TestImaging | |
{ | |
public class CompressPng | |
{ | |
public static void PngCompression() | |
{ | |
String path = @"/Users/Documents/TestData/"; | |
// Apply the product license to compress a PNG file in C# | |
License PngCompressLicense = new License(); | |
PngCompressLicense.SetLicense(path + "Conholdate.Total.Product.Family.lic"); | |
var inputPngFile = path+"Sample.png"; | |
var outputPngFile = path+"compressed_image.png"; | |
using (var PngImage = Image.Load(inputPngFile)) | |
{ | |
PngImage.Save(outputPngFile, new PngOptions | |
{ | |
// Set the compression level | |
CompressionLevel = 9, | |
Progressive = true, | |
//Set the color type | |
ColorType = PngColorType.IndexedColor, | |
Palette = ColorPaletteHelper.GetCloseImagePalette((RasterImage)PngImage, 1 << 5) | |
}); | |
} | |
} | |
} | |
} |
上面的示例可用于使用非常简单的 API 接口在 C# 中压缩 PNG 文件。 Image 类公开了多个重载函数,您可以使用这些函数从流中加载图像以及其他附加的 LoadOptions 参数以支持其他类型的图像。 PngOptions 类对象公开属性以设置颜色类型、压缩率、矢量光栅化选项等,仅举几例。
本主题教会我们开发一个可以使用 C#* 轻松执行 *PNG 压缩的应用程序。如果您想了解如何将 PNG 转换为 ICON,请参阅 如何在C#中将PNG转换为ICON 上的文章。