How can I convert a image into a byte array in uwp platform

眉间皱痕 提交于 2019-12-01 20:08:54

问题


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.


回答1:


I found the solution from these articles as theoutlander says.

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

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;

        }

you can find more in this article.



来源:https://stackoverflow.com/questions/35111635/how-can-i-convert-a-image-into-a-byte-array-in-uwp-platform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!