Xamarin.forms使用自定义cameraview重命名捕获的图像

问题描述

在我的xamarin.forms应用程序中,我有一个带有圆圈叠加层的自定义相机视图。我可以在android和iOS上拍照。我面临的困难是我需要将拍照图像重命名为包含拍照日期时间的某些特定格式。但是我无法在android和iOS上重命名拍摄的照片。

在iOS中,在我本机的cameraview中,我可以像这样获取捕获的图像。

var videoConnection = stillImageOutput.ConnectionFromMediaType(AVMediaType.Video);
                var sampleBuffer = await stillImageOutput.CaptureStillImageTaskAsync(videoConnection);
                var jpegData = AVCaptureStillImageOutput.JpegStillToNSData(sampleBuffer);
                var photo = new UIImage(jpegData);

photo包含iOS上捕获的图像。

如何重命名该图像?任何帮助表示赞赏。

解决方法

要在本地存储文件然后删除文件,请尝试以下步骤:

首先,尝试从UIImage获取文件流。

var img = new UIImage();
NSData data = img.AsPNG();
Stream output;
data.AsStream().CopyTo(output);

然后将文件与流一起保存在本地。

var documents_path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
documents_path  = Path.Combine(documents_path,"temp");
Directory.CreateDirectory(documents_path);

string filePath = Path.Combine(documents_path,name);
byte[] bytes = new byte[output.Length];
using (FileStream fs = new FileStream(filePath,FileMode.OpenOrCreate))
{
    using (output)
    {
        output.Read(bytes,(int)output.Length);
    }
    int length = bytes.Length;
    fs.Write(bArray,length);
}

使用文件路径删除文件。

if (File.Exists(filePath))
{
    File.Delete(filePath);
}