我想从 WriteableBitmap 获取 base64 字符串。我相信 byte[] 是不正确的。
因为:
从 base64 创建图像的代码正在运行。从文件发送 base64 字符串时对此进行了测试。但是,当我将 WriteableBitmap 函数用于 base64 时,我什么也看不到。
到目前为止我的尝试。
public static string GetByteArrayFromImage(WriteableBitmap writeableBitmap)
{
Stream stream = writeableBitmap.PixelBuffer.AsStream();
MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
Byte[] bytes = memoryStream.ToArray();
return Convert.ToBase64String(bytes);
}
public static string GetByteArrayFromImage(WriteableBitmap writeableBitmap)
{
Byte[] bytes = writeableBitmap.PixelBuffer.ToArray();
return Convert.ToBase64String(bytes);
}
测试示例:
public static async Task<string> GetBase64StringFromFileAsync(StorageFile storageFile)
{
Stream ms = await storageFile.OpenStreamForReadAsync();
byte[] bytes = new byte[(int)ms.Length];
ms.Read(bytes, 0, (int)ms.Length);
return Convert.ToBase64String(bytes);
}
byte[] 格式是否错误?如果是这样,我该如何纠正?
我的新尝试
Stream stream = writeableBitmap.PixelBuffer.AsStream();
byte[] pixels = new byte[(uint)stream.Length];
await stream.ReadAsync(pixels, 0, pixels.Length);
using (var writeStream = new InMemoryRandomAccessStream())
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, writeStream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, 96, 96, pixels);
await encoder.FlushAsync();
}
return Convert.ToBase64String(pixels);
此尝试不会将我的 byte[] 更改为正确的 fromat。