Android Renderscript 类型与 U8_4 不匹配

Android Renderscript Type mismatch with U8_4

我尝试从 this answer

实现 Renderscript

所以我的渲染脚本如下所示:

#pragma version(1)
#pragma rs java_package_name(bavarit.app.cinnac)

rs_allocation inImage;
int inWidth;
int inHeight;

uchar4 __attribute__ ((kernel)) rotate_90_clockwise (uchar4 in, uint32_t x, uint32_t y) {
    uint32_t inX  = inWidth - 1 - y;
    uint32_t inY = x;
    const uchar4 *out = rsGetElementAt(inImage, inX, inY);
    return *out;
}

uchar4 __attribute__ ((kernel)) rotate_270_clockwise (uchar4 in, uint32_t x, uint32_t y) {
    uint32_t inX = y;
    uint32_t inY = inHeight - 1 - x;

    const uchar4 *out = rsGetElementAt(inImage, inX, inY);
    return *out;
}

像这样的Java代码:

private static Bitmap rotateBitmapNew(Bitmap bitmap, Context ctx) {
    RenderScript rs = RenderScript.create(ctx);
    ScriptC_imageRotation script = new ScriptC_imageRotation(rs);
    script.set_inWidth(bitmap.getWidth());
    script.set_inHeight(bitmap.getHeight());
    Allocation sourceAllocation = Allocation.createFromBitmap(
            rs, bitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT
    );
    bitmap.recycle();
    script.set_inImage(sourceAllocation);

    int targetHeight = bitmap.getWidth();
    int targetWidth = bitmap.getHeight();
    Bitmap.Config config = bitmap.getConfig();
    Bitmap target = Bitmap.createBitmap(targetWidth, targetHeight, config);
    final Allocation targetAllocation = Allocation.createFromBitmap(
            rs, target, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT
    );

    script.forEach_rotate_90_clockwise(targetAllocation, targetAllocation);
    targetAllocation.copyTo(target);
    rs.destroy();
    return target;
}

但是当我调用这个函数时,我得到这个错误

android.renderscript.RSRuntimeException: Type mismatch with U8_4!

我尝试调试并找到错误,我发现来源是 ScriptC_imageRotation.java class

中的这一行
public void forEach_rotate_90_clockwise(Allocation ain, Allocation aout, Script.LaunchOptions sc) {
    // check ain
    if (!ain.getType().getElement().isCompatible(__U8_4)) {
        throw new RSRuntimeException("Type mismatch with U8_4!");
    }
    ...
}

由于我没有使用RenderScript的经验,所以只能google,但是找不到这个错误。也许你们当中有人知道。
我想我可以说的是分配的类型不正确,当我注销分配的 .getType().getElement() 时,它类似于 U_5_6_5。也许这对理解这个的人有帮助

renderscript 代码期望将 RGBA_888 作为元素类型(因为您使用 uchar4 作为 input/output 类型。)提供的 Bitmap 在RGB 565 格式,因此 createFromBitmap() 为渲染脚本 Allocation 设置的元素类型被设置为 RGB_565

您需要确保您的源 Bitmap 是 ARGB 8888 格式,因为您的目标 Bitmap 是使用源的 Bitmap.Config 创建的并且 RS 代码需要源 Allocation 也采用这种格式。