简体   繁体   中英

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. 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.

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.

This is not be a issue with those two methods. Check Convert.ToBase64String() result and what you get when you read it from database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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