简体   繁体   English

Android 位图图像到 Unity C# 纹理

[英]Android bitmap image to Unity C# texture

I'm in the draw loop of an android view:我在 android 视图的绘制循环中:

        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):将字节导入 Unity 不起作用(在我的原始图像上显示黑色图像):

        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?关于如何让 Java bytes[] 在 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.我已经测试了字节是否正确发送,即当我从 android 推送 {1,2,3,4} 的字节数组时,我在统一端得到 {1,2,3,4}。

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:这并不是说 Unity 在尝试将字节作为 byte[] 传输时会抛出错误,因此我必须在 C# 方面遵循建议:

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和 java 端的一个简单的 byte[] 容器类“Buffer”

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[].我像你一样使用 AndroidJNIHelper.ConvertFromJNIArray 进行数组转换,除了我使用 sbyte[] 而不是 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.如果我没记错的话,LoadRawTextureData 甚至比像素数据数组更原始,这可能是显卡存储压缩纹理的方式。 If that is true then raw pixel data isn't in the right format and it can't be decoded.如果这是真的,那么原始像素数据的格式不正确,无法解码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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