将Image转换为Base64字符串

时间:2018-03-28 12:32:08

标签: c# image-processing uwp base64 storagefile

我正在尝试使用getRestSonar(request).then((outputJson) => { ... do something with your outputJson ... })将图像文件转换为UWP中的Base64字符串 这是我的方法:

StorageFile

public async Task<string> ToBase64String(StorageFile file) { var stream = await file.OpenAsync(FileAccessMode.Read); var decoder = await BitmapDecoder.CreateAsync(stream); var pixels = await decoder.GetPixelDataAsync(); var bytes = pixels.DetachPixelData(); return await ToBase64(bytes, (uint)decoder.PixelWidth, (uint)decoder.PixelHeight, decoder.DpiX, decoder.DpiY); } 是这样的:

ToBase64

并从我的MainPage.xaml.cs中调用它

private async Task<string> ToBase64(byte[] image, uint pixelWidth, uint pixelHeight, double dpiX, double dpiY)
{
    //encode
    var encoded = new InMemoryRandomAccessStream();
    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, encoded);
    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, pixelWidth, pixelHeight, dpiX, dpiY, image);
    await encoder.FlushAsync();
    encoded.Seek(0);

    //read bytes
    var bytes = new byte[encoded.Size];
    await encoded.AsStream().ReadAsync(bytes, 0, bytes.Length);

    return System.Convert.ToBase64String(bytes);
}

然而,这不起作用。任何抬头?

1 个答案:

答案 0 :(得分:1)

undefined

这对我有用。