如何在 Java 中将位图转换为 PNG

这个简单的教程简要介绍了如何在 Java 中将位图转换为 PNG。通过在 Windows、macOS 和 Linux 等任何常见操作系统中编写几行代码,它将帮助您BMP 转换为 Java 中的 PNG。您还可以为输出 PNG 图像文件设置许多属性。

在 Java 中将位图转换为 PNG 的步骤

  1. 将 Maven 存储库中的 Aspose.Imaging 配置到您的项目中
  2. 将源位图文件加载到 Image 类实例中以进行转换
  3. 初始化 PngOptions 类对象以设置输出 PNG 图像属性
  4. 在 PngOptions 类对象中设置分辨率和压缩级别
  5. 设置所需属性后,将源位图文件保存为 PNG

在这些步骤中,我们加载源 BMP 文件并初始化 PngOptions 类实例以设置输出 PNG 文件的属性。在本分步教程中,我们在本教程中设置了分辨率和压缩级别,但是,也可以在生成 PNG 图像之前设置其他属性。最后,我们使用图像类的 save() 函数将 BMP 文件保存为 Java 中的 PNG。

在 Java 中将 BMP 转换为 PNG 的代码

import com.aspose.imaging.License;
import com.aspose.imaging.Image;
import com.aspose.imaging.ResolutionSetting;
import com.aspose.imaging.imageoptions.PngOptions;
public class ConvertBitmapToPNGInJava {
public static void main(String[] args) {//main function for the class ConvertBMPToPngUsingJava
// Load the Aspose.Imaging license to remove trial version message in the output PNG Image
License ImagingLicense = new License();
ImagingLicense.setLicense("Aspose.Imaging.lic");
// Load input Bitmap image file to be converted to PNG
Image BMPToPNGImage = Image.load("InputBMPImage.bmp");
// Set the attributes of the output PNG file by setting resolution and compression level
PngOptions PNGImageOptions = new PngOptions();
PNGImageOptions.setResolutionSettings( new ResolutionSetting(300, 300));
PNGImageOptions.setCompressionLevel(6);
// Save the converted output PNG image using the PngOptions object
BMPToPNGImage.save("OutputPNGImage.png", PNGImageOptions);
}
}

在这段代码中,我们只使用了分辨率和压缩属性来在 Java 中将 BMP 更改为 PNG。但是,您也可以为输出 PNG 文件设置位深度、颜色类型、过滤器类型和 XMP 元数据容器。请注意,您也可以加载任何其他类型的图像以转换为其他类型。

无需为此转换安装任何其他第三方工具。如果您想了解处理图像的其他一些功能,例如从 Excel 文件生成图像,您可以参考 如何在Java中将Excel图表转换为JPG 上的文章。

 简体中文