我正在为我的 Android 应用程序使用 NDK 和 JNI,因此我有一些原生代码。我有一个自定义适配器,其中有一个 ListView 显示来自数据库的图像和按钮。但是,该图像将由 C++ 使用。如果我单击按钮(来自 java 代码),它会将图像传递(我真的不知道这个术语)到我将使用该图像的 c++ 代码。 c++代码是否可以从Java代码访问按钮触发的图像?
我几乎是一个初学者,但这是我的最终项目,所以任何帮助将不胜感激:)
适配器.Java
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = View.inflate(mContext, R.layout.listview, null);
TextView pName = (TextView) v.findViewById(R.id.product_name);
ImageView pImage = (ImageView) v.findViewById(R.id.product_image);
TextView pPrice = (TextView) v.findViewById(R.id.product_price);
TextView pDescription = (TextView) v.findViewById(R.id.product_description);
TextView pCategory = (TextView) v.findViewById(R.id.product_category);
pName.setText(mProductList.get(position).getName());
Product image = mProductList.get(position);
final byte[] img = image.getImage();
Bitmap bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);
pImage.setImageBitmap(bitmap);
pPrice.setText("$" + String.valueOf(mProductList.get(position).getPrice()));
pDescription.setText(mProductList.get(position).getDescription());
pCategory.setText(mProductList.get(position).getCategory());
Button tryMe = (Button)v.findViewById(R.id.tryMe);
tryMe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent cameraIntent = new Intent(mContext, OpencvCamera.class);
mContext.startActivity(cameraIntent);
}
});
return v;
}
下面这段代码是我希望我的按钮将图像从数据库传递到 c++ 的地方,它将在其中与相机一起使用。在这里,按钮仅在按下时重定向到相机类。
Button tryMe = (Button)v.findViewById(R.id.tryMe);
tryMe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*WHAT SHOULD I PUT HERE FOR THE IMAGE PASSING*/
Intent cameraIntent = new Intent(mContext, OpencvCamera.class);
mContext.startActivity(cameraIntent);
}
}
下面是我的C++代码
JNIEXPORT void JNICALL Java_nerds_thesis_clartips_OpencvClass_humanDetection
(JNIEnv *, jclass, jlong addrRgba){
Mat& frame = *(Mat*)addrRgba;
detectHuman(frame);
}
void detectHuman(Mat& frame){
String human_cascade_name = "/storage/emulated/0/haarcascade_upperbody.xml";
CascadeClassifier human_cascade;
if(!human_cascade.load( human_cascade_name ) ) { printf("--(!)Error loading\n"); return; };
std::vector<Rect> humans;
Mat frame_gray;
cvtColor( frame, frame_gray, CV_BGR2GRAY );
equalizeHist( frame_gray, frame_gray);
//Detect Human
human_cascade.detectMultiScale( frame_gray, humans, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(100, 100) );
Mat imageMask = imread("/storage/emulated/0/plain.png");
/*CODE FOR OVERLAYING THE IMAGE TO THE CAMERA*/
Mat imageMask = imread("/storage/emulated/0/plain.png");
上面的行是我只为测试做的。我只声明了它,我的任何按钮都使用了相同的图像。当然会。这就是为什么我问我应该怎么做才能让我的 native 代码在我按下用 Java 代码创建的按钮时访问图像。
最佳答案
我认为在内存中传递图像对象是不可能的;但是,您可以传递对图像的引用,例如供 C++ 代码使用的 URI 或文件路径。 只需修改您的 JNI 声明即可添加该引用。
关于java - 使用 JNI 将图像从 Java 传递到 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49172991/