【问题标题】:Convert BitmapImage into Base64String in WinRT在 WinRT 中将 BitmapImage 转换为 Base64String
【发布时间】:2015-08-06 07:41:28
【问题描述】:

我想在我的 Windows 8.1 应用程序中将 BitmapImage 转换为 base64string。 代码:

protected void UpdateSignatureAsync(BitmapImage bitmapImage, string fileName, long vehicleInsRecID)
{


    WriteableBitmap writimage = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
    using (MemoryStream ms = new MemoryStream())
    {
        WriteableBitmapExtensions.FromStream(writimage, ms);
        Stream s1 = writimage.PixelBuffer.AsStream();
        s1.CopyTo(ms);
        writimage.PixelBuffer.AsStream();
        var ic = new ImageCapture
        {
            ImageBinary = Convert.ToBase64String(ms.ToArray()),/// this line
            CaseServiceRecId = vehicleInsRecID,
            FileName = fileName
        };
        await UpdateImageAsync(ic);
    }

【问题讨论】:

  • 您面临的具体问题是什么?
  • ...所以您想将图像数据保存为位图?还是您要保存原始像素?
  • 此代码错误。 BitmapImage 没有转换 WriteableBitmap 。它只是取 BitmapImage 字节数组(ms.ToArray())的高度和宽度,每个字节都是 0。
  • 您在不是async 的方法中使用了await - 您的示例代码还有其他问题。

标签: c#-4.0 windows-runtime windows-8.1 winrt-xaml winrt-async


【解决方案1】:

对于您的问题,我没有确切的答案,但如果您有一个图像 StorageFile,那么您可以使用以下类中的 GetBase64FromImageFile 方法将此图像转换为 Base64 字符串:

public static class ImageHash
{
    private static async Task<string> GetBase64FromImageFile(StorageFile file)
    {
        return ComputeHash(await ConvertToByteArray(file));
    }

    private static string ComputeHash(byte[] buffer)
    {
        IBuffer input = buffer.AsBuffer();
        IBuffer hashed = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1).HashData(input);

        return CryptographicBuffer.EncodeToBase64String(hashed);
    }

    public async static Task<byte[]> ConvertToByteArray(StorageFile imageFile)
    {
        byte[] srcPixels;
        RandomAccessStreamReference streamRef =
            RandomAccessStreamReference.CreateFromFile(imageFile);

        using (IRandomAccessStreamWithContentType fileStream =
            await streamRef.OpenReadAsync())
        {
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);
            BitmapFrame frame = await decoder.GetFrameAsync(0);

            // I know the parameterless version of GetPixelDataAsync works for this image
            PixelDataProvider pixelProvider = await frame.GetPixelDataAsync();
            srcPixels = pixelProvider.DetachPixelData();
        }

        return srcPixels;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    相关资源
    最近更新 更多