omer smoro
omer smoro

Reputation: 21

decode base64 in c# when encoding in python

I encode data of images in base64 using python before sending it to the server which is written in C#. The data that is received is identical to the data that is being sent. However, when I decode the encoded string I get a different result. Here is the code that takes a screenshot and encodes it in 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())

it is sent as is to the server and the server receives the encoded string correcetly with no data corruption.

Here is the c# code that decodes the string:

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

So does anyone know why when the data is decoded the result is incorrect?

Upvotes: 2

Views: 1667

Answers (1)

Adam Adair
Adam Adair

Reputation: 41

If it was me I would simply use the Convert.FromBase64String() and not mess with the FromBase64Transform. You don't have all the details here, so I had to improvise.

In Python I took a screen shot, encoded it, and wrote to file:

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

And in C# I decoded the file contents are wrote the binary:

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);
        }
    }
}

If you have a properly encoded byte array, then convert the array to string and then decode the string.

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);
}

Upvotes: 1

Related Questions