【问题标题】:decode base64 in c# when encoding in python在python中编码时在c#中解码base64
【发布时间】:2017-05-17 15:51:58
【问题描述】:

在将图像数据发送到用 C# 编写的服务器之前,我使用 python 在 base64 中对图像数据进行编码。接收到的数据与正在发送的数据相同。但是,当我解码编码字符串时,我得到了不同的结果。 以下是截取屏幕截图并将其编码为 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);

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

【问题讨论】:

  • 常规方式怎么样? byte[] decodedImg = Convert.FromBase64String(base64String); ?
  • 试过了。它没有用。

标签: c# python encoding base64


【解决方案1】:

如果是我,我会简单地使用 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);
}

【讨论】:

  • 我通过套接字发送图像并将其作为字节 [] 而不是作为字符串接收,因此此代码对我没有帮助。不过还是谢谢你。
  • 使用 System.Text.Encoding.UTF8.GetString() 将字节数组转换为字符串。然后解码字符串。见第二个例子。
猜你喜欢
  • 1970-01-01
  • 2011-08-13
  • 2020-04-18
  • 2016-05-28
  • 2020-04-22
  • 2023-03-16
  • 2012-12-05
  • 2011-11-14
相关资源
最近更新 更多