如何将图像转换为 jbyteArray 并返回它?

问题描述

调用 JNI 函数进行图像处理。

如果我将结果保存为文件,它工作正常。但是,当我尝试将结果作为 jbyteArray 返回时,我无法将其转换为 Bitmap 并且发生了skia 错误

D/skia (24115): --- 无法创建带有消息“未实现”的图像解码器

extern "C"
JNIEXPORT jbyteArray JNICALL
Java_com_xxx_JNIChannel_foo(jnienv *env,jobject thiz,jstring image_file,jstring out_file) {

    int width = 0;
    int height = 0;
    int channel = 0;

    const char *imagePath = env->GetStringUTFChars(image_file,0);
    const char *outPath = env->GetStringUTFChars(out_file,0);
    unsigned char* inputimage = stbi_load(imagePath,&width,&height,&channel,0);

    if ((channel != 0) && (width != 0) && (height != 0)) {
        unsigned char *outputimage = (unsigned char *) stbi__malloc(width * channel * height);

        if (inputimage) {
            memcpy(outputimage,inputimage,width * channel * height);
        } else {
            LOGD("load: %s fail!\n ",imagePath);
        }

        /////////////////////////////////////
        // image processing.. here
        /////////////////////////////////////

        // 1. File Write 
        // 
        // bool result = stbi_write_jpg(outPath,width,height,channel,outputimage,100);

        // 2. copy array 
        // 
        int len = width * height * channel;
        jbyteArray output_image = env->NewByteArray(len);
        env->SetByteArrayRegion(output_image,len,reinterpret_cast<const jbyte*>(outputimage));

        free(inputimage);
        free(outputimage);

        return output_image;
    }

    // return NULL..
}

Android Kotlin 代码

val outArr = JNIChannel.instance().foo(input.path,out.path)

val option = BitmapFactory.Options.apply {
  inJustDecodeBounds = true;
}

val bitmap = BitmapFactory.decodeByteArray(outArr,outArr.size,option)
// or 
// val bitmap = BitmapFactory.decodeByteArray(outArr,outArr.size)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)