本教程提供了有关如何在 C# 中将 JPG 转换为黑白 PDF 的详细信息。您将获得所有必要的资源来设置环境设置、重要的命名空间、类、方法和完成此任务的编程顺序。还将提供描述以自定义在 C#** 中编写 **JPG 到黑白 PDF 转换器的过程,仅借助一些 API 调用。
在 C# 中将 JPG 转换为黑白 PDF 的步骤
- 使用 NuGet 包管理器建立添加 Aspose.Imaging 的环境
- 将源 JPG 图片加载到 Image 类对象中
- 将加载的图像转换为 RasterCachedImage 类对象
- 如果未缓存,则缓存图像数据
- 使用预定义的固定阈值,对图像进行二值化
- 使用 PdfOptions 对象将生成的图像保存为 PDF
这些步骤描述了使用 C#* 逐步将 JPG 更改为黑白 PDF 的过程,首先通过将所需资源添加到项目来设置环境,然后将源 JPG 加载到 Image 类中要更改为黑白 PDF 的对象。在接下来的步骤中,将图像类型转换为 RasterCachedImage,然后将其缓存到内存中以提高性能,如果没有更早完成。最后,我们使用预定义的固定阈值对图像进行二值化,然后将最终输出保存为 PDF。
在 C# 中将 JPG 转换为黑白 PDF 的代码
using System.Drawing; | |
using Aspose.Imaging; | |
using Aspose.Imaging.ImageOptions; | |
using Image = Aspose.Imaging.Image; | |
namespace AsposeTests | |
{ | |
class Program | |
{ | |
static void Main(string[] args) // Main function to convert JPG to Black and White PDF in C# | |
{ | |
// Load Imaging license | |
Aspose.Imaging.License lic = new Aspose.Imaging.License(); | |
lic.SetLicense(@"Aspose.Total.lic"); | |
// Load the source JPG image in an instance of Image | |
using (Image image = Image.Load("sample.jpg")) | |
{ | |
// Casting the image to RasterCachedImage and checking if image is cached | |
RasterCachedImage rasterCachedImage = (RasterCachedImage)image; | |
if (!rasterCachedImage.IsCached) | |
{ | |
// Cache the image if it not already cached | |
rasterCachedImage.CacheData(); | |
} | |
// Now binarize the image with predefined fixed threshold and Save the resultant image | |
rasterCachedImage.BinarizeFixed(100); | |
PdfOptions pdfSaveOptions = new PdfOptions(); | |
rasterCachedImage.Save("BinarizationWithFixedThreshold_out.pdf", pdfSaveOptions); | |
} | |
System.Console.WriteLine("Done"); | |
} | |
} | |
} |
此代码使用 Image 类对象加载文件,用于将 JPG 转换为 C# 中的黑白 PDF,该对象不仅支持许多其他类型的图像,而且还具有多个重载函数,例如您可以从流中加载图像,而不是从文件中加载磁盘并使用附加的 LoadOptions 参数。此 LoadOptions 对象支持设置进度事件处理程序、数据恢复模式、数据背景颜色和缓冲区大小提示。
本教程教我们将 JPG 转换为黑白 PDF 文件。如果您有兴趣了解调整图像大小的过程,请参阅 如何在 C# 中调整图像大小 上的文章。