问题
So I'm able to read an image file successfully, and pass it back to my C# application but I'm unable to decode it properly.
I'm returning the JSON data as such (the json_encode function isn't shown) via PHP:
$imgbinary = fread(fopen($filename, "r"), filesize($filename));
if ( strlen($imgbinary) > 0 ){
return array("success"=>true, "map"=>base64_encode($imgbinary));
}
Then in C# I use Newtonsoft.Json to decode the string (I can read success and the map properties successfully), but I'm unable to then use base64 decode to properly write the image to a file (or to display).
I'm doing it as such:
File.WriteAllText(System.Windows.Forms.Application.StartupPath + "\\MyDir\\" + FileName, Base64Decode(FileData));
public string Base64Decode(string data)
{
byte[] binary = Convert.FromBase64String(data);
return Encoding.Default.GetString(binary);
}
Am I missing something crazy simple here? What is really strange is after I decode the data, the file size is LARGER than the original file. (I realize once you encode, data increases by about 33%, just strange that after I then decode, it is still larger).
Any help/pointers would be greatly appreciated!
回答1:
Am I missing something crazy simple here?
Yes. An image isn't a text file, so you shouldn't be using File.WriteAllText. What characters do you believe are present in an image file? It's really, really important to distinguish between when your data is fundamentally text, and when it's fundamentally binary. If you try to treat either as if it were the other, you're asking for trouble.
Don't convert back from the byte array to text (your Encoding.Default.GetString call will be losing data) - just use:
File.WriteAllBytes(path, Convert.FromBase64String(data));
来源:https://stackoverflow.com/questions/10421075/interpreting-base-64-in-c-sharp-from-an-image-based-via-json-php-base64-encode