如何在c#中将图像转换为base64string

时间:2015-12-24 11:23:49

标签: c# image xaml bitmap base64

我使用的辅助方法是....

<script id="shoe-template" type="x-handlebars-template">
{{#each people}}
    {{this.name}}
...

选择图像并转换为可写位图的代码是

private async Task<string> ToBase64(byte[] image, uint height, uint width, double dpiX = 96, double dpiY = 96)
    {
        var encoded = new InMemoryRandomAccessStream();
        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, encoded);
        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, height, width, dpiX, dpiY, image);
        await encoder.FlushAsync();
        encoded.Seek(0);

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

        return Convert.ToBase64String(bytes);
    }

    private byte[] ImageToByteArray(WriteableBitmap wbm)
    {
        using (Stream stream = wbm.PixelBuffer.AsStream())
        using (MemoryStream memoryStream = new MemoryStream())
        {
            stream.CopyTo(memoryStream);
            return memoryStream.ToArray();
        }
    }

当我将helper方法得到的base64string与http://www.dailycoding.com/utils/converter/imagetobase64.aspx进行比较时 两者都不一样。

1 个答案:

答案 0 :(得分:0)

将文件更改为“base64”

public async Task<string> GetBase64(string name)
        {
            StorageFolder folder = ApplicationData.Current.LocalFolder;
            StorageFile file = await folder.GetFileAsync(name);
            var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(file.Path));

            byte[] fileBytes = null;
            using (var stream = await file.OpenReadAsync())
            {
                fileBytes = new byte[stream.Size];
                using (var reader = new DataReader(stream))
                {
                    await reader.LoadAsync((uint)stream.Size);
                    reader.ReadBytes(fileBytes);
                }
            }

           return Convert.ToBase64String(fileBytes);
        }