在Windows应用商店应用中将图像转换为字节数组

时间:2013-10-29 11:06:40

标签: c# wpf windows-store-apps

在WindowsStoreApps中,我想将一个本地图像从解决方案资源管理器转换为字节数组,然后转换为base64 string.please引导我。到目前为止我尝试的代码如下所示。

public async Task<string> ToBase64()
{
  Byte[] ByteResult = null;

  string bs64 = null;
  if (url != null)
  {
      HttpClient client = new HttpClient();
      ByteResult = await client.GetByteArrayAsync(url);     
  }
  bs64 = Convert.ToBase64String(ByteResult);

  return bs64;
}

2 个答案:

答案 0 :(得分:3)

假设您要从Assets文件夹转换名为MyImage.png的图像,则代码下面将返回该图像的base64字符串。

private async Task DoWork()
{
    var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/MyImage.png"));
    var b64 = await ConvertStorageFileToBase64String(file);
}

private async Task<string> ConvertStorageFileToBase64String(StorageFile File)
{
    var stream = await File.OpenReadAsync();

    using (var dataReader = new DataReader(stream))
    {
        var bytes = new byte[stream.Size];
        await dataReader.LoadAsync((uint)stream.Size);
        dataReader.ReadBytes(bytes);

        return Convert.ToBase64String(bytes);
    }
} 

答案 1 :(得分:1)

试试这段代码

StorageFile file = <Your  File>;
var bytes = new Byte[0];
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
  var reader = new DataReader(fileStream.GetInputStreamAt(0));
  bytes = new Byte[fileStream.Size];
  await reader.LoadAsync((uint)fileStream.Size);
  reader.ReadBytes(bytes);
}

string imageInStringFormat = Convert.ToBase64String(bytes);