简体   繁体   English

将base64string转换回byte []

[英]Convert a base64string back to byte[]

I want to use C# to convert a byteArray to base64string by using Convert.ToBase64String() , then I want to send this string to save using MySQL by sending post data to a PHP page. 我想用C#的转换byteArraybase64string使用Convert.ToBase64String()然后我想给这个字符串使用MySQL通过邮局数据发送到PHP页面进行保存。 My problem is I can't convert this string back to a byteArray using this method as after this string is retrieved from the PHP page (after it got data from MySQL), it tells me that argument on method Convert.FromBase64String() was wrong. 我的问题是我无法使用此方法将此字符串转换回byteArray因为从PHP页检索了此字符串之后(从MySQL获取数据之后),它告诉我方法Convert.FromBase64String()上的参数错误。

I don't where is problem occurs, how can I solve it? 我不在哪里出现问题,如何解决?

My code: 我的代码:

public static string BitmapToString(BitmapImage img)
{
    try
    {
        WriteableBitmap bmp = new WriteableBitmap(img);
        byte[] byteArray = null;
        string str = null;
        MemoryStream stream = new MemoryStream();
        bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
        byteArray = stream.ToArray();
        str = Convert.ToBase64String(byteArray);
        return str;
    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.StackTrace);
    }
    return null;
}

public static BitmapImage StringToBitmap(string str)
{
    try
    {
        byte[] byteArray = Convert.FromBase64String(str);
        Stream memStream = new MemoryStream(byteArray);
        BitmapImage img = null;
        MemoryStream stream = new MemoryStream(byteArray);
        stream.Seek(0, SeekOrigin.Begin);
        img = new BitmapImage();
        img.SetSource(stream);
        return img;
    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.StackTrace);
    }
    return null;
}

Convert.FromBase64String() will work for Convert.ToBase64String() results but there can be inputs in your aplication which not converted to Base64String , those cases might fail. Convert.FromBase64String()将适用于Convert.ToBase64String()结果,但是您的应用程序中可能有一些输入未转换为Base64String ,这些情况可能会失败。

This is not be a issue with those two methods. 这两种方法都不是问题。 Check Convert.ToBase64String() result and what you get when you read it from database. 检查Convert.ToBase64String()结果以及从数据库中读取结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM