将来自Xam.Plugin.Media 5.0.1的图像源转换为Xamarinforms中的字节数组?


if (!CrossMedia.Current.IsPickPhotoSupported)
{
await Application.Current.MainPage.DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
return;
}
var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
});

if (file == null)
return;
var tmpSrc = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.Dispose();
return stream;
});

ImageSource toBeConversion = tmpSrc;

  • 我希望变量toBeConvert转换为 Byte[] 所以 我可以将其发送到我的网络 ...
ImageSource

是一种为 Xamarin.Forms.Image 提供源图像以显示某些内容的方法。如果您已经在屏幕上显示某些内容,则Image视图中填充了来自其他位置的数据,例如文件或资源或存储在内存中的数组中......或者不管你一开始就得到了它。与其尝试从ImageSource中获取该数据,不如保留对它的引用并根据需要上传。

因此,您可以在选择照片后从文件中获取字节数组。

var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
});
if (file == null)
return;    
var bytes = File.ReadAllBytes(file.Path); // you could get  the byte[] here from the file path.
  • 这段代码也对我有用...

    private async void Capture()
    {
    if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
    {
    await Application.Current.MainPage.DisplayAlert("No Camera", ":( No camera available.", "OK");
    return;
    }
    var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
    {
    Directory = "Test",
    SaveToAlbum = true,
    CompressionQuality = 75,
    CustomPhotoSize = 50,
    PhotoSize = PhotoSize.Medium,
    DefaultCamera = CameraDevice.Front
    });
    if (file == null)
    return;
    var stream = file.GetStream();
    if (stream != null)
    {
    var StreamByte = ReadAllBytes(stream);
    var NewStream = new MemoryStream(StreamByte);
    // stream = mystream;
    Device.BeginInvokeOnMainThread(() => {
    ImageSource = ImageSource.FromStream(() => NewStream);
    });
    student.ProfilePicture = StreamByte;
    }
    }
    public byte[] ReadAllBytes(Stream instream)
    {
    if (instream is MemoryStream)
    return ((MemoryStream)instream).ToArray();
    using (var memoryStream = new MemoryStream())
    {
    instream.CopyTo(memoryStream);
    return memoryStream.ToArray();
    }
    }
    

最新更新