Skip to content

Instantly share code, notes, and snippets.

@RezaAmd
Last active January 21, 2024 05:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RezaAmd/89bbc4b7c0922d783e8fee6fb879b498 to your computer and use it in GitHub Desktop.
Save RezaAmd/89bbc4b7c0922d783e8fee6fb879b498 to your computer and use it in GitHub Desktop.
// At first you should download "cwebp.exe".
// The latest source tree is available at:
// https://chromium.googlesource.com/webm/libwebp
byte[] ConvertJpgToWebP(byte[] jpgBytes, string fileName, string extension)
{
string jpgFilePath = $"images//{fileName}.{extension}";
string webpFilePath = $"images//{fileName}.webp";
// Write the JPG byte[] to a file
File.WriteAllBytes(jpgFilePath, jpgBytes);
// Invoke the cwebp command-line tool
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = "cwebp",
Arguments = $"\"{jpgFilePath}\" -o \"{webpFilePath}\"",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (Process? process = Process.Start(startInfo))
{
if (process == null)
return [];
// Wait for process.
process.WaitForExit();
}
// Read the WebP file into a byte[]
byte[] webpBytes = File.ReadAllBytes(webpFilePath);
// Delete the temporary files
File.Delete(jpgFilePath);
File.Delete(webpFilePath);
return webpBytes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment