15

所以,我有这个函数,BitmapImage我需要将它保存到 iso 存储并转换为 Base64(用于发送到服务器)。fileStream但是,从to复制memoryStream不成功。

public void SetImage(BitmapImage bitmap)
{
    if (isoFiles.FileExists(Settings.FILE_AVATAR_JPG))
        isoFiles.DeleteFile(Settings.FILE_AVATAR_JPG);

    var fileStream = isoFiles.CreateFile(Settings.FILE_AVATAR_JPG);
    var wb = new WriteableBitmap(bitmap);
    wb.SaveJpeg(fileStream, 120, 120, 0, 85); // file is saved 

    var memoryStream = new MemoryStream();
    fileStream.CopyTo(memoryStream);          // here, memoryStream is null
    byte[] result = memoryStream.ToArray();
    fileStream.Close();

    var base64 = Convert.ToBase64String(result);
}
4

1 回答 1

22

Stream.CopyTofileStream从已更改的当前位置复制,SaveJpeg()因此您需要重置它;

var memoryStream = new MemoryStream();

fileStream.Position = 0;
fileStream.CopyTo(memoryStream);  
于 2013-04-18T10:36:05.433 回答