How to Convert Images to WebP Format using C# .NET Framework
WebP might not see the same widespread use JPG and PNG format images do, but it still offers plenty of benefits — particularly for loading detailed images on web pages.
Using the below code examples, we can easily convert dozens of unique image file formats to WebP format using a free API solution. This way, we can avoid writing a lot of different code on our own, and we can minimize the resources our applications use to convert bulky files.
We can get started by installing the SDK. Let’s run this command in our package manager console to install via NuGet:
Install-Package Cloudmersive.APIClient.NET.ImageRecognition -Version 3.0.5
Next, let’s grab a free API key to authorize our API calls. This will allow us to make up to 800 API calls per month with no additional commitments; once we once we reach our limit, the total will simply reset the following month.
Last but not least, let’s go ahead and call the function to make our conversion. Let’s load in our file & copy our API key string into the appropriate snippet:
using System;
using System.Diagnostics;
using Cloudmersive.APIClient.NET.ImageRecognition.Api;
using Cloudmersive.APIClient.NET.ImageRecognition.Client;
using Cloudmersive.APIClient.NET.ImageRecognition.Model;
namespace Example
{
public class ConvertToWebPExample
{
public void main()
{
// Configure API key authorization: Apikey
Configuration.Default.AddApiKey("Apikey", "YOUR_API_KEY");
var apiInstance = new ConvertApi();
var imageFile = new System.IO.FileStream("C:\\temp\\inputfile", System.IO.FileMode.Open); // System.IO.Stream | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.
try
{
// Convert input image to WebP format
byte[] result = apiInstance.ConvertToWebP(imageFile);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling ConvertApi.ConvertToWebP: " + e.Message );
}
}
}
}
Now we can quickly & easily convert a wide range of image formats to WebP with zero hassle.