用 C# 将 HTML 转换为 JPG

JPG 文件可以无损压缩的方式包含高质量的图像数据。这种独特的压缩功能可以快速高效地共享 JPG 图像,并在网络、电脑和移动设备上广泛使用。例如,如果要在 PowerPoint 演示文稿中添加网页或通过电子邮件发送,可能需要将 HTML 文件转换为 JPG 图像。使用 Converter.ConvertHTML 方法是将 HTML 代码转换为各种格式的最常用方法。JPG 是一种常用的图像存储格式,HTML 到 JPG 的转换非常流行。使用 Aspose.HTML for .NET,您可以通过程序将 HTML 转换为 JPG 格式,并完全控制各种转换参数。

在本文中,您将了解如何使用转换器类的 ConvertHTML() 方法并应用 ImageSaveOptionsICreateStreamProvider 参数将 HTML 转换为 JPG

在线 HTML 转换器

您可以检查 Aspose.HTML for .NET API 的功能并实时转换 HTML。请从本地文件系统加载 HTML,选择输出格式并运行示例。在示例中,默认设置了保存选项。您将立即以单独文件的形式收到结果。

                
            

如果您想通过编程将 HTML 转换为 JPG,请参阅以下 C# 代码示例。

只需一行代码即可将 HTML 转换为 JPG

Converter 类的静态方法主要用作将 HTML 代码转换为各种格式的最简单方法。只需一行代码,您就可以在 C# 应用程序中将 HTML 转换为 JPG!

1// Convert HTML to JPG in C#
2
3// Invoke the ConvertHTML() method to convert the HTML code to JPG image
4Converter.ConvertHTML(@"<h1>Convert HTML to JPG!</h1>", ".", new ImageSaveOptions(ImageFormat.Jpeg), Path.Combine(OutputDir, "convert-with-single-line.jpg"));

将 HTML 转换为 JPG

使用 ConvertHTML() 方法将文件转换为另一种格式是一系列操作,其中包括文件加载和保存:

  1. 使用 HTMLDocument 类加载 HTML 文件( spring.html)。
  2. 创建一个新的带有 ImageFormat.JpegImageSaveOptions 对象。默认情况下,格式属性为 PNG
  3. 使用转换器类的 ConvertHTML() 方法将 HTML 保存为 JPG 图像。您需要向 ConvertHTML() 方法传递 HTMLDocument、ImageSaveOptions 和输出文件路径,以便将 HTML 转换为 JPG。

请看下面的 C# 代码片段,它显示了使用 Aspose.HTML for .NET 将 HTML 转换为 JPG 的过程。

 1// Convert HTML to JPG using C#
 2
 3// Prepare a path to a source HTML file
 4string documentPath = Path.Combine(DataDir, "spring.html");
 5
 6// Prepare a path to save the converted file 
 7string savePath = Path.Combine(OutputDir, "spring-output.jpg");
 8
 9// Initialize an HTML document from the file
10using HTMLDocument document = new HTMLDocument(documentPath);
11
12// Create an instance of the ImageSaveOptions class 
13ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
14
15// Convert HTML to JPG
16Converter.ConvertHTML(document, options, savePath);

图中展示的是 spring-output.jpg 文件。

文本 “spring-output.jpg 图像”

ImageSaveOptions

您可以根据自己的需要,通过保存选项来增强 JPG 图像创建功能。Aspose.HTML for .NET 允许使用默认或自定义保存选项将 HTML 转换为 JPG。使用 ImageSaveOptions 可以自定义渲染过程。您可以指定 image formatpage sizemarginsCSS media-type等。

PropertyDescription
CompressionSets Tagged Image File Format (TIFF) Compression. By default, this property is LZW.
CSSGets a CssOptions object which is used for configuration of CSS properties processing.
FormatSets the ImageFormat (JPG, PNG, BMP, TIFF, or GIF). By default, this property is PNG.
BackgroundColorThis property sets the color that will fill the background. By default, this property is Transparent.
PageSetupThis property gets a page setup object and uses it for configuration output page-set.
HorizontalResolutionSets horizontal resolution for output images in pixels per inch. The default value is 300 dpi.
VerticalResolutionSets vertical resolution for output images in pixels per inch. The default value is 300 dpi.
UseAntialiasingThis property sets the image rendering quality. Antialiasing is enabled by default.
TextGets a TextOptions object which is used for configuration of text rendering.

下面的示例展示了如何使用 ImageSaveOptions 并创建带有自定义保存选项(如页面大小和背景颜色)的输出图像:

 1// Convert HTML to JPG in C# with custom settings
 2
 3string documentPath = Path.Combine(OutputDir, "save-options.html");
 4string savePath = Path.Combine(OutputDir, "save-options-output.jpg");
 5
 6// Prepare HTML code and save it to a file
 7string code = "<h1> Image SaveOptions </h1>\r\n" +
 8              "<p>Using ImageSaveOptions Class, you can programmatically apply a wide range of conversion parameters such as BackgroundColor, Format, Compression, PageSetup, etc.</p>\r\n";
 9
10File.WriteAllText(documentPath, code);
11
12// Initialize an HTML Document from the html file
13using HTMLDocument document = new HTMLDocument(documentPath);
14
15// Set up the page-size 500x250 pixels, margins and change the background color to AntiqueWhite
16ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg)
17{
18    BackgroundColor = System.Drawing.Color.AntiqueWhite
19};
20options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(500, 250), new Margin(40, 40, 20, 20));
21
22// Convert HTML to JPG
23Converter.ConvertHTML(document, options, savePath);

要了解有关 ImageSaveOptions 类的更多信息,请阅读 微调转换器 一文。

使用图像保存选项将 HTML 转换为 JPG

使用指定的 ImageSaveOptions 将 HTML 转换为 JPG,需要遵循以下几个步骤:

  1. 使用 HTMLDocument 类的 HTMLDocument() 构造函数之一加载 HTML 文件( color.html)。
  2. 使用 JPG ImageFormat 创建一个新的 ImageSaveOptions 对象,并指定保存选项。默认情况下,格式属性为 PNG
  3. 使用转换器类的 ConvertHTML() 方法将 HTML 保存为 JPG 图像。您需要向 ConvertHTML() 方法传递 HTMLDocument、ImageSaveOptions 和输出文件路径,以便将 HTML 转换为 JPG。

下面的 C# 代码片段展示了如何使用自定义保存选项将 HTML 转换为 JPG:

 1// Convert HTML to JPG in C# with with custom background, resolution, and antialiasing settings
 2
 3// Prepare a path to a source HTML file
 4string documentPath = Path.Combine(DataDir, "color.html");
 5
 6// Prepare a path to save the converted file 
 7string savePath = Path.Combine(OutputDir, "color-output-options.jpg");
 8
 9// Initialize an HTML document from the file
10using HTMLDocument document = new HTMLDocument(documentPath);
11
12// Initialize ImageSaveOptions 
13ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg)
14{
15    UseAntialiasing = true,
16    HorizontalResolution = 200,
17    VerticalResolution = 200,
18    BackgroundColor = System.Drawing.Color.AliceBlue
19};
20options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(500, 500), new Margin(30, 20, 10, 10));
21
22// Convert HTML to JPG
23Converter.ConvertHTML(document, options, savePath);

ImageSaveOptions() 构造函数初始化 ImageSaveOptions 类的实例,并将其传递给 ConvertHTML() 方法。ConvertHTML() 方法接收 document, options, 输出文件路径 savePath 并执行转换操作。

在上述示例中,我们使用

如果您想提高应用程序中渲染的图形、文本和图像的视觉质量,尤其是对清晰度和平滑边缘要求较高时,请使用 UseAntialiasing = true。启用抗锯齿功能可通过混合边缘像素的颜色来平滑锯齿状边缘,从而使外观更柔和、更精致。

虽然 UseAntialiasing = true 可以提供更好的视觉质量,但也会增加处理时间。对于优先考虑渲染速度的应用程序,设置 UseAntialiasing = false 可能是最佳选择。

图中展示了 color-output-options.jpg 文件。

文本"“彩色” JPG 图像"

输出流提供商

如果需要将文件保存在远程存储器(如云、数据库等)中,可以实现 ICreateStreamProvider接口来手动控制文件创建过程。该接口被设计为一个回调对象,用于在文档/页面开始时创建一个流(取决于输出格式),并在渲染文档/页面后释放早期创建的流。

Aspose.HTML for .NET为渲染操作提供了多种输出格式。其中一些格式只生成一个输出文件(例如,PDFXPS),其他格式则生成多个文件(图像格式–JPGPNG等)。

下面的示例展示了如何在应用程序中实现和使用自己的MemoryStreamProvider

 1// Implement a custom MemoryStream provider for advanced control over HTML rendering output streams
 2
 3class MemoryStreamProvider : Aspose.Html.IO.ICreateStreamProvider
 4{
 5    // List of MemoryStream objects created during the document rendering
 6    public List<MemoryStream> Streams { get; } = new List<MemoryStream>();
 7
 8    public Stream GetStream(string name, string extension)
 9    {
10        // This method is called when only one output stream is required, for instance for XPS, PDF or TIFF formats
11        MemoryStream result = new MemoryStream();
12        Streams.Add(result);
13        return result;
14    }
15
16    public Stream GetStream(string name, string extension, int page)
17    {
18        // This method is called when the creation of multiple output streams are required. For instance, during the rendering HTML to list of image files (JPG, PNG, etc.)
19        MemoryStream result = new MemoryStream();
20        Streams.Add(result);
21        return result;
22    }
23
24    public void ReleaseStream(Stream stream)
25    {
26        // Here you can release the stream filled with data and, for instance, flush it to the hard-drive
27    }
28
29    public void Dispose()
30    {
31        // Releasing resources
32        foreach (MemoryStream stream in Streams)
33            stream.Dispose();
34    }
35}

下面的代码片段演示了如何使用内存流将 HTML 文件转换为 JPG 文件。

 1// Convert HTML to JPG in C# using memory stream
 2
 3// Create an instance of MemoryStreamProvider
 4using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
 5
 6// Initialize an HTML document
 7using HTMLDocument document = new HTMLDocument(@"<h1>Convert HTML to JPG File Format!</h1>", ".");
 8
 9// Convert HTML to JPG using the MemoryStreamProvider
10Converter.ConvertHTML(document, new ImageSaveOptions(ImageFormat.Jpeg), streamProvider);
11
12// Get access to the memory stream that contains the result data
13MemoryStream memory = streamProvider.Streams.First();
14memory.Seek(0, SeekOrigin.Begin);
15
16// Flush the result data to the output file
17using (FileStream fs = File.Create(Path.Combine(OutputDir, "stream-provider.jpg")))
18{
19    memory.CopyTo(fs);
20}

您可以从 GitHub 下载完整的示例和数据文件。

下载 Aspose.HTML for .NET库,它能让您成功、快速、轻松地将 HTML、MHTML、EPUB、SVG 和 Markdown 文档转换为最流行的格式。

Aspose.HTML 提供免费的在线 HTML 到 JPG 转换器,可将 HTML 转换为高质量的 JPG 图像,简单快捷。只需上传、转换您的文件,几秒钟就能得到结果!

文本 “HTML 到 JPG 转换器”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.