1

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);

この試みは、私のバイト[]を正しいフォーマットに変更しません。

4

2 に答える 2

2

以下のメソッドは、BitmapEncoderを操作する を作成し、 から作成された をInMemoryRandomAccessStream追加し、ストリーム コンテンツをバイト配列に読み取り、最後にそのバイト配列を base64 文字列に変換します。SoftwareBitmapWriteableBitmap

public async Task<string> ToBase64String(WriteableBitmap writableBitmap)
{
    using (var stream = new InMemoryRandomAccessStream())
    {
        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

        encoder.SetSoftwareBitmap(SoftwareBitmap.CreateCopyFromBuffer(
            writableBitmap.PixelBuffer,
            BitmapPixelFormat.Bgra8,
            writableBitmap.PixelWidth,
            writableBitmap.PixelHeight));

        await encoder.FlushAsync();

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

        return Convert.ToBase64String(bytes);
    }
}
于 2016-05-05T20:34:36.197 に答える