从 Xamarin Android 文档中的字节数组创建图像文件

问题描述:

有人可以帮助我了解如何从 Xamarin Android 文档中的字节数组创建图像文件并获取图像的新路径吗?

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 ?

这是我的代码:

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();

现在 picData 是字节数组,我需要在文档中创建一个 Jpeg 文件并获取新路径..提前谢谢.

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

您可以使用 MemoryStream 绕过并将 Android Bitmap 直接解码/压缩为 FileStream 节省资源(内存和处理时间):

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();