在这个简单的主题中,您将探索如何使用 NET REST API 将 JPG 转换为 WEBP。我们将遵循下面提到的详细步骤,使用 C# Low Code API 开发一个 JPG 到 WEBP 转换器。开发的应用程序代码可以与 macOS、Windows 或 Linux 环境中支持的任何 .NET 应用程序集成,并且可以免费进行转换。
先决条件
创建账户并获取 API 凭证 执行 JPG 到 WEBP 的转换
下载 Aspose.Imaging Cloud SDK for .NET to convert JPG to WEBP
使用上述 SDK 设置 C# .NET 项目,将 JPG 渲染为 WEBP
使用 NET REST API 将 JPG 转换为 WEBP 的步骤
- 设置 API 的客户端 ID 和客户端密钥以将 JPG 转换为 WEBP
- 使用客户端凭据创建 ImagingAPI 类的实例,以执行 JPG 到 WEBP 的转换
- 指定源 JPG 和输出 WEBP 文件名
- 访问并打开示例 JPG 文件并将其上传到云存储
- 使用输入 JPG 文件流和输出 WEBP 格式创建 ConvertImageRequest 实例
- 调用 ConvertImage 方法使用 NET REST API 将 JPG 转换为 WEBP
- 将返回的WEBP文件流保存在本地磁盘
下面介绍了使用 C# Low Code API 将文件类型从 JPG 导出为 WEBP 的步骤。我们将通过使用 ImagingAPI 类的实例提供订阅凭据来初始化 SDK。然后,我们将使用磁盘中的 FileStream 打开源 JPG 文件,然后使用 ConvertImageRequest 类实例使用 ConvertImage() 方法执行到 WEBP 的转换。
使用 NET Low Code API 进行 JPG 到 WEBP 转换的代码
using Aspose.Imaging.Cloud.Sdk.Api; | |
using Aspose.Imaging.Cloud.Sdk.Model.Requests; | |
using Aspose.Imaging.Cloud.Sdk.Model; | |
using System; | |
using System.IO; | |
namespace Kb_Aspose.KB | |
{ | |
public class JpgToWebpConverter | |
{ | |
public void JpgToWebp() | |
{ | |
var clientID = "Client ID"; | |
var clientSecret = "Client Secret"; | |
var apiBaseUrl = "https://api.aspose.cloud"; | |
var localPath = "C:/Words/"; | |
var jpgToWebpImageApi = new ImagingApi(clientSecret, clientID, apiBaseUrl); | |
// Source and output file names | |
var inputFileName = "Sample.jpg"; | |
var outputFileName = "JpgtoWebp.webp"; | |
var outputFormat = "webp"; | |
var remoteFolder = null; // source file is saved at the root of the storage | |
var remoteStorage = null; // remote cloud Storage place name | |
try | |
{ | |
// Upload the local image to Cloud Storage | |
var inpuFileStream = File.Open(localPath + '/' + inputFileName, FileMode.Open); | |
inpuFileStream.Position = 0; | |
var uploadJpgFileRequest = new UploadFileRequest(inputFileName, inpuFileStream, null); | |
jpgToWebpImageApi.UploadFile(uploadJpgFileRequest); | |
var convertJpgToWebpRequest = new ConvertImageRequest(inputFileName, outputFormat, | |
remoteFolder, remoteStorage); | |
var webpDataStream = jpgToWebpImageApi.ConvertImage(convertJpgToWebpRequest); | |
webpDataStream.Position = 0; | |
using (var fileStream = File.Create(localPath + outputFileName + "." + outputFormat)) | |
{ | |
webpDataStream.Seek(0, SeekOrigin.Begin); | |
webpDataStream.CopyTo(fileStream); | |
} | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine(e.Message); | |
} | |
} | |
} | |
} |
这个简洁的代码示例展示了如何使用 C# Cloud API 将 JPG 转换为 WEBP。完成先决条件步骤后,您必须提供访问磁盘上源 JPG 图像的路径,并使用 Aspose.Imaging REST API SDK 执行对 WEBP 的渲染。转换完成后,将收到渲染的 WEBP 图像文件流作为响应,然后您可以将其本地保存在磁盘上。
在本文中,我们学习了使用 Cloud API 将 JPG 转换为 WEBP。如果您想执行 JPG 到 TIFF 的转换,请参阅有关如何 使用 NET REST API 将 JPG 转换为 TIFF 的文章。