简体   繁体   中英

Android bitmap image to Unity C# texture

I'm in the draw loop of an android view:

        Bitmap bitmap = Bitmap.createBitmap(this.getWidth(), 
        this.getHeight(), Bitmap.Config.ARGB_4444);
        Canvas newCanvas = new Canvas(bitmap);
        super.draw(newCanvas);
        Log.d("AndroidUnity","Canvas Drawn!");
        mImageView.setImageBitmap(bitmap);

And the above code shows me the correct drawing on the attached Image Viewer.

When I convert the bitmap to a byte array:

        ByteBuffer byteBuffer = ByteBuffer.allocate(bitmap.getByteCount());
        bitmap.copyPixelsToBuffer(byteBuffer);
        byte[] bytes = byteBuffer.array();

importing the bytes into Unity does not work (shows a black image on my rawimage):

        imageTexture2D = new Texture2D(width, height, TextureFormat.ARGB4444, false);
        imageTexture2D.LoadRawTextureData(bytes);
        imageTexture2D.Apply();
        RawImage.texture = imageTexture2D;

Any ideas on how to get the Java bytes[] to display as a texture/image in Unity? I've tested that the bytes are sending correctly, ie when I push a byte array of {1,2,3,4} from android, I get {1,2,3,4} on the unity side.

this isn't mentioning that Unity throws an error when trying to transfer the bytes as a byte[], so instead I have to follow this advice, on the C# side:

void ReceieveAndroidBytes(AndroidJavaObject jo){
AndroidJavaObject bufferObject = jo.Get<AndroidJavaObject>("Buffer");
byte[] bytes = AndroidJNIHelper.ConvertFromJNIArray<byte[]>(bufferObject.GetRawObject()); }

and a trivial byte[] container class "Buffer" on the java side

I was trying to do the exact same thing and my initial attempts also had a black texture. I do the array conversion with AndroidJNIHelper.ConvertFromJNIArray like you do except I used sbyte[] instead of byte[]. To set the actual image data I ended up using

imageTexture2D.SetPixelData(bytes, 0);

If I'm not mistaken LoadRawTextureData is even rawer than an array of pixel data, it might be how graphics cards store textures with compression. If that is true then raw pixel data isn't in the right format and it can't be decoded.

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