1

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 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but I tried your code and nothing happend. any help please. I need create a new image from byte array in documents folder xamarin android
@XamaX Which Document directory are you looking in? My sample would save it to the app's documents (i.e. /storage/emulated/0/Android/data/your.app.packagenamehere/files/Documents/sameImagePath.jpg) If you need a different directory update the path accordingly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.