c# - 在 python 中编码时在 c# 中解码 base64

标签 c# python encoding base64

我使用 python 对图像数据进行 base64 编码,然后将其发送到用 C# 编写的服务器。接收到的数据与正在发送的数据相同。然而,当我解码编码的字符串时,我得到了不同的结果。 以下是截取屏幕截图并将其编码为 Base64 的代码:

screen_shot_string_io = StringIO.StringIO()
ImageGrab.grab().save(screen_shot_string_io, "PNG")
screen_shot_string_io.seek(0)
return base64.b64encode(screen_shot_string_io.getvalue())

它按原样发送到服务器,服务器正确接收编码的字符串,没有数据损坏。

这是解码字符串的 C# 代码:

byte[] decodedImg = new byte[bytesReceived];
FromBase64Transform transfer = new FromBase64Transform();
transfer.TransformBlock(encodedImg, 0, bytesReceived, decodedImg, 0);

那么有谁知道为什么数据解码时结果不正确?

最佳答案

如果是我,我会简单地使用 Convert.FromBase64String()不要弄乱 FromBase64Transform。您这里没有所有详细信息,所以我不得不即兴发挥。

在 Python 中,我拍摄了屏幕截图,对其进行编码,然后写入文件:

# this example converts a png file to base64 and saves to file
from PIL import ImageGrab
from io import BytesIO
import base64

screen_shot_string_io = BytesIO()
ImageGrab.grab().save(screen_shot_string_io, "PNG")
screen_shot_string_io.seek(0)
encoded_string = base64.b64encode(screen_shot_string_io.read())
with open("example.b64", "wb") as text_file:
    text_file.write(encoded_string)

在 C# 中,我解码了文件内容并写入了二进制文件:

using System;
using System.IO;

namespace Base64Decode
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] imagedata = Convert.FromBase64String(File.ReadAllText("example.b64"));
            File.WriteAllBytes("output.png",imagedata);
        }
    }
}

如果您有正确编码的字节数组,请将数组转换为字符串,然后对字符串进行解码。

public static void ConvertByteExample()
{
    byte[] imageData = File.ReadAllBytes("example.b64");
    string encodedString = System.Text.Encoding.UTF8.GetString(imageData); //<-- do this
    byte[] convertedData = Convert.FromBase64String(encodedString); 
    File.WriteAllBytes("output2.png", convertedData);
}

关于c# - 在 python 中编码时在 c# 中解码 base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44029583/

相关文章:

c# - 从静态函数写入标签

python - 根据特定元组值删除列表中的元素

c++ - 从 SinkWriter 或 ICodecAPI 或 IMFTransform 获取编码器名称

python - cx_Oracle 游标忘记聚合时的列比例

python - 什么是 "ANSI_X3.4-1968"编码?

java - 在 Tomcat 服务器上使用 POST 方法从 jsp 到 jsp 的错误编码

c# - List.clear() 后跟 List.add() 不起作用

C# 我无法从数据库检索路径在图片框中显示图片

c# - CLR 触发器只更新特定的列

python - 如何使用 Python 的 pyOpenSSL 创建和签署证书?