简体   繁体   中英

Bitmap to Base64String

i am trying to convert a bitmap to a base64 string.i can convert to from string to bitmap...but it seems like there is a problem when converting from bitmap to string.I was hoping you guys could give me a hand

    public static string BitmapToString(BitmapImage image)
    {

        Stream stream = image.StreamSource ;
        Byte[] buffer = null;
        if (stream != null && stream.Length > 0)
        {
            using (BinaryReader br = new BinaryReader(stream))
            {
                buffer = br.ReadBytes((Int32)stream.Length);
            }
        }

        return Convert.ToBase64String(buffer);
    }

it gets a ArgumentNullException was unhandled Value cannot be null. Parameter name: inArray when returning Convert.ToBase64String(buffer)

Help?

Try this alternative:

 public string BitmapToBase64(BitmapImage bi)
        {
            MemoryStream ms = new MemoryStream();
            PngBitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bi));
            encoder.Save(ms);
            byte[] bitmapdata = ms.ToArray();

            return Convert.ToBase64String(bitmapdata);
        }

In your solution, it is not necessary that StreamSource will always have value if it is loaded using a Uri.

First of all, it is necessary to save BitmapImage data into memory using some bitmap encoder ( PngBitmapEncoder for example).

public static byte[] EncodeImage(BitmapImage bitmapImage)
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        BitmapEncoder encoder = new PngBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
        encoder.Save(memoryStream);
        return memoryStream.ToArray();
    }
}

Then just encode the binary data with Base64-encoding.

const string filePath = @"...";
const string outFilePath = @"...";
const string outBase64FilePath = @"...";

// Constuct test BitmapImage instance.
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = File.OpenRead(filePath);
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();

// Convert BitmapImage to byte array.
byte[] imageData = EncodeImage(bitmapImage);
File.WriteAllBytes(outFilePath, imageData);

// Encode with Base64.
string base64String = Convert.ToBase64String(imageData);

// Write to file (for example).
File.WriteAllText(outBase64FilePath, base64String);

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