2017-05-17 3 views
1

C#で書かれたサーバに送る前に、pythonを使ってbase64で画像のデータをエンコードします。受信されるデータは、送信されるデータと同一です。しかし、コード化された文字列をデコードすると、私は別の結果を得ます。デコードbase64 in c#Pythonでエンコーディングする場合

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()) 

それが送信されるサーバであり、サーバがないデータの破損とcorrecetlyエンコードされた文字列を受信する: ここではスクリーンショットを取り、BASE64でそれをコードするコードです。ここで

は、文字列をデコードするC#のコードです:データが復号されたとき、結果が間違っている理由

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

だから誰もが知っているのですか?

+0

従来の方法はどうですか? 'byte [] decodedImg = Convert.FromBase64String(base64String);'? –

+0

それを試してみてください。それはうまくいかなかった。 –

答えて

1

私の場合は、単にを使用し、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); 
} 
+0

私はソケットを通して画像を送信し、文字列ではなくバイト[]として受け取るので、このコードは役に立ちません。 しかし、とにかくありがとうございます。 –

+0

System.Text.Encoding.UTF8.GetString()を使用して、バイト配列をstringに変換します。次に、文字列をデコードします。 2番目の例を参照してください。 –

関連する問題