May 22, 2024

Srikaanth

any options to reduce image quality of webp format using asp.net mvc 5

 SixLabors.ImageSharp not work in asp.net mvc 5 so any other options to reduce image quality of webp format


The error `CS1503: Argument 2: cannot convert from 'SkiaSharp.SKWebpEncoderOptions' to 'int'` indicates that the `Encode` method is being called with incorrect parameters. Specifically, it expects an integer (representing quality) rather than an instance of `SKWebpEncoderOptions`.


To resolve this, we need to use the `SKImage.Encode` method correctly for encoding the image in WebP format with specified quality settings. 


Here’s the corrected method using `SkiaSharp`:


1. **Ensure necessary using directives**:


    ```csharp

    using SkiaSharp;

    using SkiaSharp.WebP;

    using System;

    using System.Collections.Generic;

    using System.IO;

    using System.Net.Http;

    using System.Text.RegularExpressions;

    using System.Threading.Tasks;

    ```


2. **Corrected `SaveImagesToFolder` method**:


    ```csharp

    public async Task SaveImagesToFolder(List<string> imageUrls, string title)

    {

        if (imageUrls.Count > 0)

        {

            int i = 1;

            using (var client = new HttpClient())

            {

                foreach (var imageUrl in imageUrls)

                {

                    try

                    {

                        string fpattern = "[^a-zA-Z_]+";

                        string replacement = " ";


                        string folderPath = Path.Combine("E:\\Imagesfolder", title);

                        Directory.CreateDirectory(folderPath);


                        HttpResponseMessage response = await client.GetAsync(imageUrl);

                        response.EnsureSuccessStatusCode();

                        byte[] imageBytes = await response.Content.ReadAsByteArrayAsync();


                        string imageName = Regex.Replace(Path.GetFileNameWithoutExtension(new Uri(imageUrl).LocalPath), fpattern, replacement).Trim();

                        string magen = title + " " + i;

                        string imagePath = Path.Combine(folderPath, magen + ".webp");


                        // Load the image using SkiaSharp

                        using (var inputStream = new MemoryStream(imageBytes))

                        using (var bitmap = SKBitmap.Decode(inputStream))

                        using (var image = SKImage.FromBitmap(bitmap))

                        using (var outputStream = new FileStream(imagePath, FileMode.Create, FileAccess.Write))

                        {

                            // Create WebP encoder options with quality set to 50

                            var webpEncoderOptions = new SKWebpEncoderOptions(SKWebpEncoderCompression.Lossy, 50);


                            // Encode the image to WebP format

                            var encodedData = image.Encode(SKEncodedImageFormat.Webp, 50);

                            encodedData.SaveTo(outputStream);

                        }

                        i++;

                    }

                    catch (Exception ex)

                    {

                        // Handle exceptions, e.g., image download failed

                        Console.WriteLine($"Error downloading image from {imageUrl}: {ex.Message}");

                    }

                }

            }

        }

    }

    ```


### Explanation


- **Using `SKImage.Encode`**:

  - `image.Encode(SKEncodedImageFormat.Webp, 50)` encodes the image to WebP format with a quality of 50.

  - `SaveTo(outputStream)` writes the encoded data to the specified output stream.


- **Creating WebP Encoder Options**:

  - `new SKWebpEncoderOptions(SKWebpEncoderCompression.Lossy, 50)` creates the WebP encoder options with lossy compression and quality set to 50.


- **Writing to File**:

  - A `FileStream` is used to write the encoded image data to the specified file path.


### Key Points


- **Quality Setting**: Adjusted to 50 using the `SKWebpEncoderOptions`.

- **File Handling**: Correctly handling file streams for writing the encoded image data.

- **Error Handling**: Captures and logs any errors during the download and processing stages.


### Required Packages


Ensure you have the necessary `SkiaSharp` packages installed via NuGet:


```bash

Install-Package SkiaSharp

Install-Package SkiaSharp.NativeAssets.Linux

Install-Package SkiaSharp.NativeAssets.Win

Install-Package SkiaSharp.Views.WindowsForms

Install-Package SkiaSharp.WebP

```


By using this approach, you can successfully save images in WebP format with reduced quality using `SkiaSharp` in your ASP.NET MVC 5 application.

Subscribe to get more Posts :