create image file from byte array in documents Xamarin Android

冷暖自知 提交于 2019-12-24 09:59:06

问题


Could anyone help me about how to create image file from byte array in documents Xamarin Android and get the new path for the image please ?

Here my code :

Stream stream = ContentResolver.OpenInputStream(data.Data);
Bitmap bitmap = BitmapFactory.DecodeStream(stream);
MemoryStream memStream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 50, memStream);
byte[] picData;
picData = memStream.ToArray();

now picData is byte array, and I need to create a Jpeg file in doucments and get the new path .. Thanks advance.


回答1:


You can bypass using a MemoryStream and decode/compress an Android Bitmap directly to a FileStream to save resources (memory and processing time):

var bitmap = BitmapFactory.BitmapFactory.DecodeStream(stream);
var path = Path.Combine(GetExternalFilesDir(Environment.DirectoryDocuments).AbsolutePath, "sameImagePath.jpg");
if (!File.Exists(path))
{
    using (var filestream = new FileStream(path, FileMode.Create))
    {
        if (bitmap.Compress(Bitmap.CompressFormat.Jpeg, 50, filestream))
        {
            filestream.Flush();
        }
        else {} // handle failure case...
    }
}
bitmap.Recycle();
bitmap.Dispose();


来源:https://stackoverflow.com/questions/43899497/create-image-file-from-byte-array-in-documents-xamarin-android

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