位图到Base64String

时间:2012-03-15 19:07:35

标签: c# wpf string image bitmap

我正在尝试将位图转换为base64 string.i可以转换为从字符串到位图...但似乎从位图转换为字符串时出现问题。我希望你们能给我一个手

    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);
    }

它得到一个未处理的ArgumentNullException 值不能为空。 参数名称:inArray 返回Convert.ToBase64String(缓冲区)

帮助?

2 个答案:

答案 0 :(得分:2)

尝试这个替代方案:

 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.

答案 1 :(得分:1)

首先,有必要使用一些位图编码器(BitmapImage)将PngBitmapEncoder数据保存到内存中。

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();
    }
}

然后用Base64编码对二进制数据进行编码。

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);