本主题重点介绍如何在 Java 中压缩 PNG。它包含所有必需的资源、类、方法和一个工作示例代码,以**使用 Java **压缩 PNG。生成的应用程序可以在 Windows、macOS 或 Linux 内的任何 Java 兼容环境中使用。
使用 Java 压缩 PNG 的步骤
- 通过使用存储库管理器添加 Aspose.Imaging for Java 来设置环境
- 使用 Image 类的实例加载源 PNG 图像文件
- 使用 PngOptions 类的实例来设置压缩率以及其他属性
- 将压缩的 PNG 文件保存在磁盘上
通过遵循上述步骤,您可以使用循序渐进的方法轻松管理 Java* 中的 *PNG 压缩,我们通过在项目中包含所需资源来初始配置环境。然后,我们将使用 Image 类的实例从磁盘访问源 PNG 图像,然后使用 PngOptions 类的实例来配置压缩率以及其他相关属性。最后,压缩后的 PNG 图像将根据 Pngoptions 设置保存在磁盘上。
使用 Java 压缩 PNG 的代码
import com.aspose.imaging.ColorPaletteHelper; | |
import com.aspose.imaging.Image; | |
import com.aspose.imaging.ImageOptionsBase; | |
import com.aspose.imaging.License; | |
import com.aspose.imaging.RasterImage; | |
import com.aspose.imaging.fileformats.png.PngColorType; | |
import com.aspose.imaging.imageoptions.PngOptions; | |
public class CompressPNG { | |
public static void main (String[] args) { | |
String path = "/Users/Documents/KnowledgeBase/TestData/"; | |
// Applying product license to Compress a PNG image in Java | |
License pngCompressionLicense = new License(); | |
pngCompressionLicense.setLicense(path + "Conholdate.Total.Product.Family.lic"); | |
String inputPngFile = path+"Sample.png"; | |
String outputPngFile = path+"compressed_image.png"; | |
Image image = Image.load(path + "sample.png"); | |
Image pngImage = Image.load(inputPngFile); | |
PngOptions options = new PngOptions(); | |
// Set the compression level | |
options.setCompressionLevel(9); | |
options.setProgressive(true); | |
//Set the colour type | |
options.setColorType(PngColorType.IndexedColor); | |
options.setPalette(ColorPaletteHelper.getCloseImagePalette((RasterImage)pngImage, 1 << 5)); | |
pngImage.save(outputPngFile,options); | |
} | |
} |
此示例代码可用于使用非常简单的 API 调用在 Java 中压缩 PNG 文件。 Image 类包含多个重载函数,这些函数可用于从流中加载图像,并结合其他 LoadOptions 参数以支持其他类型的图像。 PngOptions 类公开了设置颜色类型、压缩比、矢量光栅化选项等属性的方法,仅举几例。
在本主题中,我们了解了如何使用 Java* 实现 *PNG 压缩。如果您有兴趣了解如何将 PNG 转换为 ICON,请参阅 如何在 Java 中将 PNG 转换为 ICON 上的文章。