如何从Unity3D访问本机Java位图?

时间:2017-01-11 16:12:42

标签: unity3d bitmap native native-code

我想使用在我的Unity项目中加载到我的本机Java库中的位图。

如何将位图从Java传递到C#?

1 个答案:

答案 0 :(得分:0)

由于您不是非常具体的问题,我假设您将图片加载为BufferedImage。所以这里有一个关于如何做的建议:

使用JNA Library可以更好地访问c#的资源。

然后可能做类似的事情:

BufferedImage someImage;
long somePointer;

DataBuffer data = someImage.getData().getDataBuffer();
int[] bankOffsets = data.getOffsets();
long offset = 0;
com.sun.jna.Pointer ptr = new com.sun.jna.Pointer(somePointer);
switch(data.getDataType()) {
case DataBuffer.TYPE_BYTE: 
    byte[][] bbanks = ((DataBufferByte) data).getBankData();
    for (int i = 0; i < bbanks.length; i++, offset += bbanks[i].length - bankOffsets[i]) 
        ptr.write(offset, bbanks[i], bankOffsets[i], bbanks[i].length - bankOffsets[i]);
break;
case DataBuffer.TYPE_DOUBLE:
    double[][] dbanks = ((DataBufferDouble) data).getBankData();
    for (int i = 0; i < dbanks.length; i++, offset += (dbanks[i].length - bankOffsets[i])*8) 
        ptr.write(offset, dbanks[i], bankOffsets[i], dbanks[i].length - bankOffsets[i]);
break;
case DataBuffer.TYPE_FLOAT:
    float[][] fbanks = ((DataBufferFloat) data).getBankData();
    for (int i = 0; i < fbanks.length; i++, offset += (fbanks[i].length - bankOffsets[i])*4) 
        ptr.write(offset, fbanks[i], bankOffsets[i], fbanks[i].length - bankOffsets[i]);
break;
case DataBuffer.TYPE_INT:
    int[][] ibanks = ((DataBufferInt) data).getBankData();
    for (int i = 0; i < ibanks.length; i++, offset += (ibanks[i].length - bankOffsets[i])*4) 
        ptr.write(offset, ibanks[i], bankOffsets[i], ibanks[i].length - bankOffsets[i]);
break;
case DataBuffer.TYPE_SHORT:
    short[][] sbanks = ((DataBufferShort) data).getBankData();
    for (int i = 0; i < sbanks.length; i++, offset += (sbanks[i].length - bankOffsets[i])*2) 
        ptr.write(offset, sbanks[i], bankOffsets[i], sbanks[i].length - bankOffsets[i]);
break;
case DataBuffer.TYPE_USHORT:
    short[][] usbanks = ((DataBufferUShort) data).getBankData();
    for (int i = 0; i < usbanks.length; i++, offset += (usbanks[i].length - bankOffsets[i])*2) 
        ptr.write(offset, usbanks[i], bankOffsets[i], usbanks[i].length - bankOffsets[i]);
break;
case DataBuffer.TYPE_UNDEFINED:
    throw new IllegalArgumentException("Unsupported data type");
}

写入的数据应该是您所有的像素颜色值。格式取决于图像类型(可以使用类getType()中的BufferedImage方法获取。

或者您也可以使用Java Native Interface,但我还没有考虑过。