【问题标题】:File Compression Type changes when converting image to base64将图像转换为 base64 时文件压缩类型发生变化
【发布时间】:2021-11-03 04:45:13
【问题描述】:

我有一个压缩类型为 CCITT T.6 的图像,该图像被转换为​​ base64 并发送到后端 API,其中 base64 字符串将被转换回原始图像并验证文件详细信息。我的问题是,当我将 base64 字符串转换回其原始图像时,图像的压缩类型现在已更改为 LZW。将图像转换为 base64 字符串会改变其压缩类型吗?如果是这样,我怎样才能保持文件的原始压缩类型。

string img = "";       
using (Image image = Image.FromFile(filepath))
{
    using (MemoryStream m = new MemoryStream())
    {
        image.Save(m, image.RawFormat);
        byte[] imageBytes = m.ToArray();

        // Convert byte[] to Base64 String
        string base64String = Convert.ToBase64String(imageBytes);
        img = base64String;
    }
}

LoadImage(img);

 public void LoadImage(string base64image)
 {
     byte[] bytes = Convert.FromBase64String(base64image);
     Image image;
     using (MemoryStream ms = new MemoryStream(bytes))
     {
         image = Image.FromStream(ms);
     }
     File.WriteAllBytes(filepath,bytes);
 }

【问题讨论】:

  • 看起来(网络)服务器正在接受 LZW?那么客户端压缩上传?我猜是这样的
  • 这似乎不是您的实际代码。 File.WriteAllBytes() 在那里做什么?从流中加载后,您似乎没有对 image 做任何事情。 --- 不,转换为/从 Base64 本身不会改变图像的压缩方法。
  • 啊抱歉 File.WriteAllBytes() 是让我保存图像并通过文件资源管理器检查实际文件详细信息。我的实际代码将返回图像并对文件详细信息进行一些验证。
  • base64 转换肯定不会改变图像格式。我会看看你的第一种方法,你正在加载图像并保存到内存流中。为什么不返回Convert.ToBase64String(File.ReadAllBytes(filepath))

标签: c# base64


【解决方案1】:

摆脱内存流并使用 Steeeve 建议的Convert.ToBase64String(File.ReadAllBytes(filepath)) 似乎已经解决了这个问题。从 base64 字符串重新生成图像后,图像压缩类型现在保持一致。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    相关资源
    最近更新 更多