Convert webp base64 to jpg/png base64 C#

huangapple go评论77阅读模式
英文:

Convert webp base64 to jpg/png base64 C#

问题

使用以下代码将WebP图像转换为JPG或PNG格式,然后返回其Base64字符串

英文:

i have a problem that the client has the webp saved in base64 in the database, but to print the image i needed it to be in jpg or png, with that i thought of taking the image, converting it to an byte array and converting the image, changing the base64 for printing.

using (Image image = Image.FromStream(new MemoryStream(Convert.FromBase64String(base64))))
{
   image.Save("output.jpg", ImageFormat.Jpeg);  // Or Png
}

i've tried with this code, but after this i don't know what make, detail, i don't need to save the image, i only want the conversion and after return the base64 of jpg or png.

答案1

得分: 0

这段代码基本上解决了问题。使用 ImageMagick 库将 WebP 图像转换为 JPG 图像,然后将其编码为 Base64 字符串。详细代码如下:

using System.IO;
using ImageMagick;

using (var stream = new MemoryStream(byteArray))
{
    using (var image = new MagickImage(stream))
    {
        // 将 WebP 图像转换为 JPG 图像
        using (var outputStream = new MemoryStream())
        {
            image.Format = MagickFormat.Jpeg;
            image.Quality = 80;
            image.Write(outputStream);

            return Convert.ToBase64String(outputStream.ToArray());
        }
    }
}

我发现了 MagickImage Lib,并将图像存储在内存中的 MemoryStream 中,因此无需将图像保存到磁盘,因为图像保留在内存中。这个方法适用于我的需求,解决了这个问题。感谢所有试图帮助的人!

英文:

well, i solved the problem basically with this code

using System.IO;
using ImageMagick;

using (var stream = new MemoryStream(byteArray))
{
    using (var image = new MagickImage(stream))
    {
        // Convert the WebP image to a JPG image
        using (var outputStream = new MemoryStream())
        {
            image.Format = MagickFormat.Jpeg;
            image.Quality = 80;
            image.Write(outputStream);

            return Convert.ToBase64String(outputStream.ToArray());
        }
   }

}

i discover the MagickImage Lib, and record the image in memomry with the memoryStream, so with this i don't need save the image to migrate, because the image stay in the memory, she works well for that i need and solved this question, thanks to everyone who tried to help Convert webp base64 to jpg/png base64 C#

huangapple
  • 本文由 发表于 2023年2月23日 22:21:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75546089.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定