简体   繁体   中英

How does one get the MAUI.Graphics.IImage object from image picked from mediaPicker?

I have been trying to get Microsoft.Maui.Graphics.IImage object from the image I picked using Microsoft.Maui.Media.MediaPicker .

I tried to use

var file = await MediaPicker.PickPhotoAsync(new MediaPickerOptions
            {
                Title = "Pick a photo"
            });

var memoryStream = new MemoryStream();
var filestream = await file.OpenReadAsync();
await filestream.CopyToAsync(memoryStream);

byte[] byteArray = memoryStream.ToArray();
Microsoft.Maui.Graphics.IImage image;
Microsoft.Maui.Graphics.IImage newImage;
image = Microsoft.Maui.Graphics.Platform.PlatformImage.FromStream(memoryStream);

if (image != null)
{
    newImage = image.Resize(720, 1280, ResizeMode.Stretch, true);
}

Now, the execution throws the error "Object not set to an instance of the object". I debugged and saw that although the photo was being picked and was being loaded into the Memory Stream, the 'image' variable does not store the data after being assigned the value in the line:

image = Microsoft.Maui.Graphics.Platform.PlatformImage.FromStream(memoryStream);

The condition:

if (image != null)

returns true, but using the resize function throws the "Object not set to an instance of the object" error.

why don't you use your byte array?

Try something like this:

Stream stream = await photo.OpenReadAsync();

stream.Position = 0;
byte[] byteArray;

using (BinaryReader br = new BinaryReader(stream))
{
   byteArray = br.ReadBytes((int)stream.Length);
}

And so, use LoadImageFromBytes Here the documentation

Hope it helps.

Thanks for replies. For now, I have used the platforms specific code to use Android.Graphics.Bitmap class and iOS UIImage class respectively for each platform. This enables me to store the image in platform specific class objects instead of finding a multi platform class to store the image and resize it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM