本文提供了有关如何在 C# 中从 PDF 中获取图像的详细信息,并借助配置详细信息和可运行的示例代码。共享完整的程序逻辑,可用于编写此应用程序,因为提供了所有必要的类和方法,这些类和方法是从 C# 中以 JPEG、PNG 等不同格式获取图像所需的。您还将通过在从 PDF 文件中获取输出图像后自定义输出图像来学习不同的选项来增强该过程。
在 C# 中获取 PDF 图像的步骤
- 将 IDE 配置为使用 Aspose.PDF for .NET 从 PDF 中提取图像
- 使用 Document 类对象加载包含图像的源 PDF 文件
- 使用 XImage 类对象访问特定图像
- 使用所需图像的名称创建新文件流
- 将图像另存为 JPEG 并关闭流
这些步骤通过共享分步方法解释如何在 C# 中从 PDF 获取图像,首先我们加载源 PDF 文件,然后访问 PDF 的特定页面。每个页面都有一个资源集合,包括可以在索引的帮助下引用的图像。一旦将所需的图像引用访问到 XImage 类对象中,就可以将其作为图像以任何所需格式保存到流中。
在 C# 中从 PDF 中获取图像的代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Aspose.Pdf; | |
using System.Drawing.Imaging; | |
using System.IO; | |
namespace AsposeProjects | |
{ | |
class Program | |
{ | |
static void Main(string[] args) // Main function to get images from a PDF file | |
{ | |
// Initialize license | |
Aspose.Pdf.License lic = new Aspose.Pdf.License(); | |
lic.SetLicense("Aspose.Total.lic"); | |
// Load the document | |
Document pdfDocument = new Document("SampleInput.pdf"); | |
// Get the desired image | |
XImage xImage = pdfDocument.Pages[1].Resources.Images[20]; | |
FileStream outputImage = new FileStream("output.jpg", FileMode.Create); | |
// Save output image | |
xImage.Save(outputImage, ImageFormat.Jpeg); | |
outputImage.Close(); | |
System.Console.WriteLine("Done"); | |
} | |
} | |
} |
此代码演示了在 C#* 中通过将图像加载到 Document 类对象中*从 PDF 中获取图像的过程,然后获取特定页面的资源列表,然后从资源中获取该页面上的图像列表。一旦我们有权访问特定图像,我们就可以重命名图像以及文档中引用的更改。您还可以获得不同的属性,如名称、高度和宽度,以在将图像保存到磁盘之前对其进行过滤。
本教程指导我们从 PDF 页面中提取图像。如果您想了解在 PDF 文件中添加水印的过程,请参阅 如何在 C# 中为 PDF 添加水印 上的文章。