如何在 uwp 平台中将图像转换为字节数组 [英] How can I convert a image into a byte array in uwp platform

查看:46
本文介绍了如何在 uwp 平台中将图像转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将图像转换为字节数组以将其存储在数据库中.而且我还需要将该数组转换回图像.我做了谷歌研究,但我找不到解决方案,因为在 UWP 平台中,某些 api 不可用.

I need to convert an image into a byte array to store it in a database. and also I need to convert that array back to the image. I did google research but I couldn't find a solution because in UWP platform some api doesn't available.

推荐答案

我从这些文章中找到了解决方案 theoutlander说.

I found the solution from these articles as theoutlander says.

要将图像转换为字节[],我将使用存储文件的OpenSequentialReadAsyn()"方法.

To convert a image into a byte[] i'm going to use the 'OpenSequentialReadAsyn()' method of a storage file.

假设我们的图像是文件".要将其转换为字节数组,请执行以下操作

lets assume that our image is 'file'. to convert it into a byte array do the below

 using (var inputStream = await file.OpenSequentialReadAsync())
        {
            var readStream = inputStream.AsStreamForRead();

            var byteArray =  new byte[readStream.Length];
            await readStream.ReadAsync(byteArray, 0, byteArray.Length);
            return byteArray;
        }

要将 byte[] 转换回图像,请执行以下操作,

To convert the byte[] back into a image do the following,

 using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
        {
            using (DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0)))
            {
                writer.WriteBytes(this.byteArray);
                await writer.StoreAsync();
            }
            var image = new BitmapImage();
            await image.SetSourceAsync(stream);
            return image;

        }

您可以在这篇文章中找到更多信息.

这篇关于如何在 uwp 平台中将图像转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆