C
C#3y ago
khamas

Recursively compressing image as webp

long len = image.Length;
using var readStream = image.OpenReadStream();
MemoryStream tmpImageStream = null;
bool firstRun = true;
while (len > maxLen)
{
// !!!! ERROR IS HERE !!!!
using var tmpISImage = SixLabors.ImageSharp.Image.Load(firstRun ? readStream : tmpImageStream, firstRun ? new JpegDecoder() : new WebpDecoder());
var newWidth = (int)Math.Round(tmpISImage.Width / 1.35, 0, MidpointRounding.ToNegativeInfinity);
var newHeight = (int)Math.Round(tmpISImage.Height / 1.35, 0, MidpointRounding.ToNegativeInfinity);
tmpISImage.Mutate(x => x.Resize(newWidth, newHeight));

if (tmpImageStream is null)
{
tmpImageStream = new();
}
else
{
tmpImageStream.Dispose();
tmpImageStream = new();
}

tmpISImage.SaveAsWebp(tmpImageStream);

len = tmpImageStream.Length;

if (firstRun) firstRun = false;
}
}

long len = image.Length;
using var readStream = image.OpenReadStream();
MemoryStream tmpImageStream = null;
bool firstRun = true;
while (len > maxLen)
{
// !!!! ERROR IS HERE !!!!
using var tmpISImage = SixLabors.ImageSharp.Image.Load(firstRun ? readStream : tmpImageStream, firstRun ? new JpegDecoder() : new WebpDecoder());
var newWidth = (int)Math.Round(tmpISImage.Width / 1.35, 0, MidpointRounding.ToNegativeInfinity);
var newHeight = (int)Math.Round(tmpISImage.Height / 1.35, 0, MidpointRounding.ToNegativeInfinity);
tmpISImage.Mutate(x => x.Resize(newWidth, newHeight));

if (tmpImageStream is null)
{
tmpImageStream = new();
}
else
{
tmpImageStream.Dispose();
tmpImageStream = new();
}

tmpISImage.SaveAsWebp(tmpImageStream);

len = tmpImageStream.Length;

if (firstRun) firstRun = false;
}
}

1 Reply
khamas
khamasOP3y ago
when it goes into the second iteration of the loop I get Invalid WebP data when I load the image I just want to convert my image to webp and compress it a bit I forgot to set the stream position to 0 😐
Want results from more Discord servers?
Add your server