这个简短的教程包含有关如何在 Java 中将 JPG 转换为黑白 PDF 的所有信息。提供了完整的描述,如环境配置、编程方法和可运行的示例代码,以在 Java 中开发JPG 到黑白 PDF 转换器。此外,还共享了不同的选项,可用于在任何支持 Java 的操作系统中自定义此转换过程。
使用 Java 将 JPG 更改为黑白 PDF 的步骤
- 建立环境以从存储库中为 Java 添加 Aspose.Imaging
- 将源 JPG 图像加载到 Image class 对象中以转换为黑白 PDF
- 将此加载的图像转换为 RasterCachedImage 类以访问必要的功能
- 检查图像是否已缓存,如果尚未缓存则将其缓存
- 使用带有预定义固定阈值的 binarizeFixed() 方法对加载的图像进行二值化
- 使用 PdfOptions 对象将生成的图像保存为 PDF 文件以进行自定义
上述步骤指导建立环境,然后介绍编写完整应用程序以将 JPG 转换为 Java 中的黑白 PDF 的详细过程。它解释了如何加载源图像,并将其转换为 RasterCachedImage 类的对象,以访问所需的二值化和缓存方法。同一类包含将图像转换为目标 PDF 的 save 方法。
在 Java 中将 JPG 转换为黑白 PDF 的代码
import com.aspose.imaging.Image; | |
import com.aspose.imaging.RasterCachedImage; | |
import com.aspose.imaging.imageoptions.PdfOptions; | |
public class AsposeTest { | |
public static void main(String[] args) throws Exception {//Main function to convert JPG to Black and White PDF | |
// Instantiate the license | |
com.aspose.imaging.License slidesLicense = new com.aspose.imaging.License(); | |
slidesLicense.setLicense("Aspose.Total.lic"); | |
// Load the source image for conversion to PDF | |
try (Image image = Image.load("sample.jpg")) | |
{ | |
// Cast the loaded image to RasterCachedImage | |
RasterCachedImage rasterImage = (RasterCachedImage)image; | |
// Check if the loaded image is cached | |
if (!rasterImage.isCached()) | |
{ | |
// Cache the loaded image for performance | |
rasterImage.cacheData(); | |
} | |
// Using the binarizeFixed() method binarize the loaded image | |
rasterImage.binarizeFixed((byte) 100); | |
// Declare the PdfOptions object | |
PdfOptions pdfOptions = new PdfOptions(); | |
// Save the PDF image | |
rasterImage.save("BinarizedImage.pdf",pdfOptions); | |
} | |
System.out.println("Done"); | |
} | |
} |
此代码演示了将 JPG 转换为 Java 中的黑白 PDF 的过程,其中 Image 类用于加载源 JPG 文件。请注意,您可以使用 canLoad() 方法检查是否可以加载图像,还可以使用 LoadOptions 类对象设置加载图像的各种属性,例如设置数据恢复模式和设置进度事件处理程序。同样,一旦图像被加载,您可以调整图像大小、旋转图像,甚至可以根据需要通过设置背景等方式对其进行修改。
本教程指导我们从 Java 中的图像创建黑白 PDF。如果您想了解调整图像大小的过程,请参阅 如何使用Java调整图像大小 上的文章。