Unable to find PixelFormat Enum for Xamarin Android

411 views Asked by At

I have the below code where i am creating a ImageReader instance in xamarin android, how to change Image Format from ImageFormatType.Rgb565 to PixelFormat.RGBA_8888

i am unable to find the Library or a Enum class for it.

mImageReader = ImageReader.NewInstance(windowWidth, windowHeight, ImageFormatType.Rgb565, 2)
3

There are 3 answers

7
SushiHangover On BEST ANSWER

You need to pass an int value of 3 (Android.Graphics.Format.Rgb888) to ImageReader.NewInstance, but currently you can not.

That is a bug/issue in Xamarin.Android auto-generation API process as they do not create a overload that accepts an Android.Graphics.Format enum, or just a plain int as the Java API does.

You can do this the same way you would do it in Java via Xamarin.Android's binding to Android.Runtime.JNIEnv or Java.Lang.Reflect

Example using JNI:

Note: Using JNI requires that the assembly be allowed to use "unsafe" code ( on the plus side, JNI is faster execution than using reflection...)

public static class ImageReaderEx
{
    public unsafe static ImageReader NewInstance(int width, int height, Android.Graphics.Format format, int maxImages)
    {
        JniArgumentValue* ptr = stackalloc JniArgumentValue[4];
        *ptr = new JniArgumentValue(width);
        ptr[1] = new JniArgumentValue(height);
        ptr[2] = new JniArgumentValue((int)format);
        ptr[3] = new JniArgumentValue(maxImages);
        JniPeerMembers _members = new XAPeerMembers("android/media/ImageReader", typeof(ImageReader));
        return Java.Lang.Object.GetObject<ImageReader>(_members.StaticMethods.InvokeObjectMethod("newInstance.(IIII)Landroid/media/ImageReader;", ptr).Handle, JniHandleOwnership.TransferLocalRef);
    }

    public unsafe static ImageReader NewInstance(int width, int height, int format, int maxImages)
    {
        JniArgumentValue* ptr = stackalloc JniArgumentValue[4];
        *ptr = new JniArgumentValue(width);
        ptr[1] = new JniArgumentValue(height);
        ptr[2] = new JniArgumentValue(format);
        ptr[3] = new JniArgumentValue(maxImages);
        JniPeerMembers _members = new XAPeerMembers("android/media/ImageReader", typeof(ImageReader));
        return Java.Lang.Object.GetObject<ImageReader>(_members.StaticMethods.InvokeObjectMethod("newInstance.(IIII)Landroid/media/ImageReader;", ptr).Handle, JniHandleOwnership.TransferLocalRef);
    }
}

Usage:

var imageReader = ImageReaderEx.NewInstance(1, 1, 3, 1);

or

var ImageReader = ImageReaderEx.NewInstance(1, 1, Android.Graphics.Format.Rgb888, 1);
1
navylover On

In Xamarin, its Format.Rgba8888 (lower case). the doc is here

0
Jaspion On

Another option is to use this:

var imageReader = ImageReader.NewInstance(_mWidth, _mHeight, (ImageFormatType)Format.Rgba8888, 2);

It's working for me.