将图像转换为 Base64 字符串
Convert Image to Base64 string
我正在尝试使用 StorageFile
在 UWP 中将图像文件转换为 Base64 字符串
这是我的方法:
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
是这样的:
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);
}
并从我的 MainPage.xaml.cs
调用它
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
string square_b64 = converter.ToBase64String(await storageFolder.GetFileAsync("Image.png")).Result;
但是,这不起作用。有什么注意事项吗?
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile file1 = await storageFolder.GetFileAsync("Image.png");
string _b64 = Convert.ToBase64String(File.ReadAllBytes(file1.Path));
这对我有用。
我正在尝试使用 StorageFile
在 UWP 中将图像文件转换为 Base64 字符串
这是我的方法:
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
是这样的:
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);
}
并从我的 MainPage.xaml.cs
调用它StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
string square_b64 = converter.ToBase64String(await storageFolder.GetFileAsync("Image.png")).Result;
但是,这不起作用。有什么注意事项吗?
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile file1 = await storageFolder.GetFileAsync("Image.png");
string _b64 = Convert.ToBase64String(File.ReadAllBytes(file1.Path));
这对我有用。