2

I had Converted Jpg to Webp But I want to resize the image.

using (Bitmap bitmap = new Bitmap(UploadName +jpgFileName))
{
    using (var saveImageStream = System.IO.File.Open(webpFileName, FileMode.Create))
    {
        var encoder = new SimpleEncoder();
        encoder.Encode(bitmap, saveImageStream, 90);
    }
}
4b0
  • 21,981
  • 30
  • 95
  • 142

1 Answers1

1

I think you can first resize in jpg then you convert from jpg to webp.

those methods i use to resize image:


You can recive a IFormFile jpgImage and convert to byte[] using method below:

public byte[] GetBytes(IFormFile formFile)
        {
            using var fileStream = formFile.OpenReadStream();
            var bytes = new byte[formFile.Length];
            fileStream.Read(bytes, 0, (int)formFile.Length);

            return bytes;
        }

// Methods to resize the jpg image in byte[]
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

...

public byte[] ResizeImage(byte[] img, int width, int height)
        {
            using var image = SixLabors.ImageSharp.Image.Load(img);
            var options = new ResizeOptions
            {
                Size = new Size(width, height),
                Mode = ResizeMode.Max
            };
            return Resize(image, options);
  }

private byte[] Resize(Image<Rgba32> image, ResizeOptions resizeOptions)
    {
        byte[] ret;

        image.Mutate(i => i.Resize(resizeOptions));

        using MemoryStream ms = new MemoryStream();
        image.SaveAsJpeg(ms);

        ret = ms.ToArray();
        ms.Close();

        return ret;
    }

After resize the jpg image in byte[] you convert to webp

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 01 '22 at 22:54
  • Wouldn't you loose less information if you converted the file to webp first and resized after that? Feels to me like shrinking in jpg reduces the overall result, but not sure about it. – Andreas Aug 23 '22 at 07:33