英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论