C# - Base64 byte array to Image FAILS no matter what I try

后端 未结 1 476
谎友^
谎友^ 2021-01-03 07:11

I\'m having trouble creating an Image/Bitmap object in C# from a base64 encoded byte array.

Here\'s what I\'m dealing with:


I have a f

相关标签:
1条回答
  • 2021-01-03 07:42

    I think your problem is that you are taking a base64 string that was posted to your controller , treating it like ASCII, and then converting it to base64 again.

    I think you need to change this line

    byte[] imageBytes = Convert.FromBase64String(imageData.EncodeTo64());
    

    to

    byte[] imageBytes = Convert.FromBase64String(imageData);
    

    from there your bytes should be correct and you should be able to create your image

    --Edit--

    I took the sample data you provided in the text document and parsed it before loading it into a Bitmap. I was able to save the image to my hard drive and was greeted by a Spartan (Go Green!!)

    Give this code a try and see what happens.

    Please note imageData is exactly what's exposed on http://kristianbak.com/test_image.txt. I would have provided the initialization, but it's a pretty big string and would probably break things.

    string imageDataParsed = imageData.Substring( imageData.IndexOf( ',' ) + 1 );
    byte[] imageBytes = Convert.FromBase64String( imageDataParsed );
    using ( var imageStream = new MemoryStream( imageBytes, false ) )
    {
       Bitmap image = new Bitmap( imageStream );
    }
    
    0 讨论(0)
提交回复
热议问题