在 Windows 应用商店应用中将图像转换为字节数组
本文关键字:应用 转换 字节 字节数 数组 图像 Windows | 更新日期: 2023-09-27 18:37:12
在WindowsStoreApps中,我想将本地映像从解决方案资源管理器转换为字节数组,然后转换为base64字符串。请指导我。到目前为止,我尝试的代码如下。
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;
}
假设您要从资产文件夹中转换名为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);
}
}
试试这段代码
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);