使用camera2 API获取单张图像并用ImageView显示

2023-12-26

我想使用 Camera2 API 从相机获取单个帧并使用 ImageView 显示它。 我发现了一些密切的问题,例如

https://stackoverflow.com/questions/25462277/camera-preview-image-data-processing-with-android-l-and-camera2-api https://stackoverflow.com/questions/25462277/camera-preview-image-data-processing-with-android-l-and-camera2-api

我还查看了 Camera2Basic 示例,但它太复杂并且不完全是我所需要的。

我编写的代码是基于我在网上看到的一些示例,应该可以实现,但它不起作用,我不明白为什么。

应用程序不会崩溃,但只是不在 ImageView 上显示任何内容。 我在任何函数调用中都使用了日志消息,以便尝试保持 logcat 清晰。

另外,该应用程序是 logcat 说“该应用程序可能在后台做了太多工作......”我不明白这怎么可能,因为我做了一个captureRequest而不是一个repeatingCaptureRequest.

这是代码和 logcat: 代码:

public class CameraImageReaderActivity extends AppCompatActivity {

private final static String TAG = "CAMERA_IMAGE_READY: ";
private ImageReader imageReader;
private String cameraId;
private CameraDevice camera;
private HandlerThread handlerThread;
private Handler handler;
private Surface imageReaderSurface;
private ImageView imageView;

private CameraDevice.StateCallback cameraStateCallback = new CameraDevice.StateCallback() {
    @Override
    public void onOpened(CameraDevice cameraDevice) {
        Log.d(TAG, "onOpend: CAMERA OPENED");
        camera = cameraDevice;
        getFrames();
    }

    @Override
    public void onDisconnected(CameraDevice cameraDevice) {
        Log.d(TAG, "onDisconnected: CAMERA DISCONNECTED");
        cameraDevice.close();
        camera = null;
    }

    @Override
    public void onError(CameraDevice cameraDevice, int i) {
        Log.d(TAG, "onError: CAMERA ERROR");
        cameraDevice.close();
        camera = null;
    }
};

private CameraCaptureSession.StateCallback captureSessionStateCallback = new CameraCaptureSession.StateCallback() {
    @Override
    public void onConfigured(CameraCaptureSession cameraCaptureSession) {
        Log.d(TAG, "onConfigured: build request and capture");
        try {
            CaptureRequest.Builder requestBuilder = cameraCaptureSession.getDevice().createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
            requestBuilder.addTarget(imageReaderSurface);

            cameraCaptureSession.capture(requestBuilder.build(), null, handler);
        } catch (CameraAccessException e) {
            Log.d(TAG, "onConfigured: CANT CREATE CAPTURE REQUEST");
            e.printStackTrace();
        }
    }

    @Override
    public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) {
        Log.d(TAG, "onConfiguredFailed: CANT CONFIGURE CAMERA");
    }
};

private ImageReader.OnImageAvailableListener imageReaderListener = new ImageReader.OnImageAvailableListener() {
    @Override
    public void onImageAvailable(ImageReader imageReader) {
        Log.d(TAG, "onImageAvailable: IMAGE AVAILABLE");
        Image image = imageReader.acquireLatestImage();
        int imgFormat = image.getFormat();
        ByteBuffer pixelArray1 = image.getPlanes()[0].getBuffer();
        int pixelStride = image.getPlanes()[0].getPixelStride();
        int rowStride = image.getPlanes()[0].getRowStride();
        int rowPadding = rowStride - pixelStride * 640;

        Bitmap bitmap = Bitmap.createBitmap(640 + rowPadding/pixelStride, 480, Bitmap.Config.RGB_565);
        bitmap.copyPixelsFromBuffer(pixelArray1);
        imageView.setImageBitmap(bitmap);

        image.close();
    }
};

/**
 * Sets the cameraId with the front camera id and sets imageReader properties.
 */
public void setupCamera(int width, int height) {
    imageReader = ImageReader.newInstance(width, height, ImageFormat.RGB_565, 30);
    CameraManager cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);
    try {
        for (String allCamerasId : cameraManager.getCameraIdList()) {
            CameraCharacteristics cameraCharacteristics = cameraManager.getCameraCharacteristics(allCamerasId);
            if (cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT) {
                continue;
            }
            cameraId = allCamerasId;
            Log.d(TAG, "setupCamera: CameraId is: " + cameraId);
            return;
        }
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

}

/**
 * Connects to the front facing camera.
 * After the connection to the camera, the onOpened callback method will be invoked.
 */
public void connectCamera() {
    CameraManager cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);
    try {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            Log.d(TAG, "CANT OPEN CAMERA");
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        cameraManager.openCamera(cameraId, cameraStateCallback, handler);
        Log.d(TAG, "connectCamera: CAMERA OPENED!");
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

/**
 * Build the captureSessionRequest and start in repeat.
 */
public void getFrames() {
    Log.d(TAG, "getFrames: CREATE CAPTURE SESSION");
    imageReaderSurface = imageReader.getSurface();
    List<Surface> surfaceList = new ArrayList<>();
    surfaceList.add(imageReaderSurface);
    try {
        camera.createCaptureSession(surfaceList, captureSessionStateCallback, handler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

public void startBackgroundThread() {
    handlerThread = new HandlerThread("CameraImageReaderActivity");
    handlerThread.start();
    handler = new Handler(handlerThread.getLooper());
}

public void stopBackgroundThread() {
    handlerThread.quitSafely();
    try {
        handlerThread.join();
        handlerThread = null;
        handler = null;
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public void closeCamera() {
    if (camera != null) {
        camera.close();
        camera = null;
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera_image_reader);
    imageView = (ImageView) findViewById(R.id.imageView);
    setupCamera(640, 480);
    connectCamera();
}

@Override
protected void onPause() {
    closeCamera();
    startBackgroundThread();
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();
    startBackgroundThread();
    //connectCamera();
}

以及(相关的)logcat:

03-22 14:27:32.900 18806-18806/com.example.noamm_000.talkwithcompviawifi D/CAMERA_IMAGE_READY:: setupCamera: CameraId is: 0
03-22 14:27:32.904 18806-18806/com.example.noamm_000.talkwithcompviawifi W/ArrayUtils: Ignoring invalid value mw_continuous-picture
03-22 14:27:32.905 18806-18806/com.example.noamm_000.talkwithcompviawifi W/ArrayUtils: Ignoring invalid value emboss
03-22 14:27:32.905 18806-18806/com.example.noamm_000.talkwithcompviawifi W/ArrayUtils: Ignoring invalid value sketch
03-22 14:27:32.905 18806-18806/com.example.noamm_000.talkwithcompviawifi W/ArrayUtils: Ignoring invalid value neon
03-22 14:27:32.905 18806-18806/com.example.noamm_000.talkwithcompviawifi W/ArrayUtils: Ignoring invalid value asd
03-22 14:27:32.905 18806-18806/com.example.noamm_000.talkwithcompviawifi W/ArrayUtils: Ignoring invalid value backlight
03-22 14:27:32.905 18806-18806/com.example.noamm_000.talkwithcompviawifi W/ArrayUtils: Ignoring invalid value flowers
03-22 14:27:32.905 18806-18806/com.example.noamm_000.talkwithcompviawifi W/ArrayUtils: Ignoring invalid value AR
03-22 14:27:32.912 18806-18806/com.example.noamm_000.talkwithcompviawifi I/CameraManager: Using legacy camera HAL.
03-22 14:27:33.685 18806-18806/com.example.noamm_000.talkwithcompviawifi W/ArrayUtils: Ignoring invalid value mw_continuous-picture
03-22 14:27:33.685 18806-18806/com.example.noamm_000.talkwithcompviawifi W/ArrayUtils: Ignoring invalid value emboss
03-22 14:27:33.685 18806-18806/com.example.noamm_000.talkwithcompviawifi W/ArrayUtils: Ignoring invalid value sketch
03-22 14:27:33.685 18806-18806/com.example.noamm_000.talkwithcompviawifi W/ArrayUtils: Ignoring invalid value neon
03-22 14:27:33.686 18806-18806/com.example.noamm_000.talkwithcompviawifi W/ArrayUtils: Ignoring invalid value asd
03-22 14:27:33.686 18806-18806/com.example.noamm_000.talkwithcompviawifi W/ArrayUtils: Ignoring invalid value backlight
03-22 14:27:33.686 18806-18806/com.example.noamm_000.talkwithcompviawifi W/ArrayUtils: Ignoring invalid value flowers
03-22 14:27:33.686 18806-18806/com.example.noamm_000.talkwithcompviawifi W/ArrayUtils: Ignoring invalid value AR
03-22 14:27:33.702 18806-18806/com.example.noamm_000.talkwithcompviawifi D/CAMERA_IMAGE_READY:: connectCamera: CAMERA OPENED!
03-22 14:27:33.719 18806-18806/com.example.noamm_000.talkwithcompviawifi I/Choreographer: Skipped 56 frames!  The application may be doing too much work on its main thread.
03-22 14:27:33.787 18806-18806/com.example.noamm_000.talkwithcompviawifi D/CAMERA_IMAGE_READY:: onOpend: CAMERA OPENED
03-22 14:27:33.787 18806-18806/com.example.noamm_000.talkwithcompviawifi D/CAMERA_IMAGE_READY:: getFrames: CREATE CAPTURE SESSION
03-22 14:27:33.789 18806-18806/com.example.noamm_000.talkwithcompviawifi I/CameraDeviceState: Legacy camera service transitioning to state CONFIGURING
03-22 14:27:33.789 18806-19149/com.example.noamm_000.talkwithcompviawifi I/RequestThread-0: Configure outputs: 1 surfaces configured.
03-22 14:27:33.790 18806-19149/com.example.noamm_000.talkwithcompviawifi D/Camera: app passed NULL surface
03-22 14:27:33.838 18806-18806/com.example.noamm_000.talkwithcompviawifi I/CameraDeviceState: Legacy camera service transitioning to state IDLE
03-22 14:27:33.843 18806-19150/com.example.noamm_000.talkwithcompviawifi D/CAMERA_IMAGE_READY:: onConfigured: build request and capture
03-22 14:27:33.874 18806-19149/com.example.noamm_000.talkwithcompviawifi W/LegacyRequestMapper: convertRequestMetadata - control.awbRegions setting is not supported, ignoring value
03-22 14:27:33.875 18806-19149/com.example.noamm_000.talkwithcompviawifi W/LegacyRequestMapper: Only received metering rectangles with weight 0.
03-22 14:27:33.875 18806-19149/com.example.noamm_000.talkwithcompviawifi W/LegacyRequestMapper: Only received metering rectangles with weight 0.
03-22 14:27:34.070 18806-18806/com.example.noamm_000.talkwithcompviawifi I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@13c07070 time:331143683
03-22 14:27:34.317 18806-19155/com.example.noamm_000.talkwithcompviawifi I/CameraDeviceState: Legacy camera service transitioning to state CAPTURING
03-22 14:27:34.353 18806-19149/com.example.noamm_000.talkwithcompviawifi I/CameraDeviceState: Legacy camera service transitioning to state IDLE
03-22 14:27:34.403 18806-18806/com.example.noamm_000.talkwithcompviawifi D/BubblePopupHelper: isShowingBubblePopup : false
03-22 14:27:34.403 18806-18806/com.example.noamm_000.talkwithcompviawifi D/BubblePopupHelper: isShowingBubblePopup : false
03-22 14:27:34.404 18806-18806/com.example.noamm_000.talkwithcompviawifi D/BubblePopupHelper: isShowingBubblePopup : false
03-22 14:27:34.404 18806-18806/com.example.noamm_000.talkwithcompviawifi D/BubblePopupHelper: isShowingBubblePopup : false
03-22 14:28:07.684 18806-18823/com.example.noamm_000.talkwithcompviawifi E/BufferQueueProducer: [unnamed-18806-1] cancelBuffer: BufferQueue has been abandoned
03-22 14:28:07.684 18806-18822/com.example.noamm_000.talkwithcompviawifi E/BufferQueueProducer: [unnamed-18806-1] cancelBuffer: BufferQueue has been abandoned
03-22 14:28:07.684 18806-19184/com.example.noamm_000.talkwithcompviawifi E/BufferQueueProducer: [unnamed-18806-1] cancelBuffer: BufferQueue has been abandoned
03-22 14:28:07.685 18806-18823/com.example.noamm_000.talkwithcompviawifi E/BufferQueueProducer: [unnamed-18806-1] cancelBuffer: BufferQueue has been abandoned
03-22 14:28:07.685 18806-18822/com.example.noamm_000.talkwithcompviawifi E/BufferQueueProducer: [unnamed-18806-1] cancelBuffer: BufferQueue has been abandoned
03-22 14:28:07.685 18806-19184/com.example.noamm_000.talkwithcompviawifi E/BufferQueueProducer: [unnamed-18806-1] cancelBuffer: BufferQueue has been abandoned
03-22 14:28:07.686 18806-18823/com.example.noamm_000.talkwithcompviawifi E/BufferQueueProducer: [unnamed-18806-1] cancelBuffer: BufferQueue has been abandoned
03-22 14:28:07.686 18806-18822/com.example.noamm_000.talkwithcompviawifi E/BufferQueueProducer: [unnamed-18806-1] cancelBuffer: BufferQueue has been abandoned

谢谢, 诺姆


尝试这种方法更好地在后台线程中处理它。

 public void onImageAvailable(ImageReader reader) {
        new ImageSaver(reader.acquireLatestImage());
    } 

   private class ImageSaver implements Runnable {

        private final Image mImage;

        public ImageSaver(Image image) {
            mImage = image;
        }

        @Override
        public void run() {
            File mImageFileName = null;
            if (mImage != null) {

                ByteBuffer byteBuffer = mImage.getPlanes()[0].getBuffer();
                byte[] bytes = new byte[byteBuffer.remaining()];
                byteBuffer.get(bytes);

                FileOutputStream fileOutputStream = null;
                try {
                    mImageFileName = createImageFileName();
                    fileOutputStream = new FileOutputStream(mImageFileName);
                    fileOutputStream.write(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    mImage.close();
                    if (mImageFileName != null) {
                        Intent mediaStoreUpdateIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        mediaStoreUpdateIntent.setData(Uri.fromFile(mImageFileName));
                        sendBroadcast(mediaStoreUpdateIntent);
                        loadImageFromStorage(mImageFileName);
                    }
                    if (fileOutputStream != null) {
                        try {
                            fileOutputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

        private void loadImageFromStorage(File mImageFileName) {
            imageView.setImageBitmap(BitmapFactory.decodeFile(mImageFileName.getAbsolutePath()));
        }
    }

    private File createImageFileName() throws IOException {
        String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String prepend = "IMAGE_" + timestamp + "_";
        File imageFile = File.createTempFile(prepend, ".jpg", createImageFolder());
        return imageFile;
    }

    private File createImageFolder() {
        File imageFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File mImageFolder = new File(imageFile, "myFolder");
        if (!mImageFolder.exists()) {
            mImageFolder.mkdirs();
        }
        return mImageFolder;
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用camera2 API获取单张图像并用ImageView显示 的相关文章

  • Eclipse Android 项目总是在调试中启动

    我觉得问这个问题很愚蠢 遇到这个问题更愚蠢 我有一个 Android 项目 到目前为止一直运行良好 但几天前 在我没有做任何我所知道的特别事情的情况下 无论我尝试什么 我的项目总是在调试中启动自己 单击调试或运行会给我相同的结果 我尝试查看
  • Gradle 错误:在操作系统独立路径“META-INF/androidx.localbroadcastmanager_localbroadcastmanager.version”中找到多个文件

    我需要android 图像裁剪器我的 Android 应用程序的库 所以我将其添加到 gradle 依赖项中 同步后 出现了一些错误 这是一个 gradle 无法修复 发现多个文件具有与操作系统无关的路径 META INF androidx
  • 在第一个框中输入字符后,将焦点转到下一个框

    我必须实现一个应用程序 其中我设置了较小的值edittext用于输入 PIN 码和手机号码 每个编辑文本一次包含 1 个字符 现在 当我运行这个应用程序时 我发现对于每个框 我需要将焦点放在每个框上edittext 因此 在这种情况下 是否
  • 使用busybox在后台安装apk

    我可以在 root 设备上使用 busybox 在后台安装 apk 吗 我看到类似的东西 但它不起作用 process install CommandCapture command new CommandCapture 0 chmod 77
  • 如何在android中批量插入sqlite

    我正在使用 SQLiteOpenHelper 进行数据插入 我需要插入2500个id和2500个名字 所以花费了太多时间 请任何人帮助我如何减少插入时间 我们可以一次插入多条记录吗 任何人都可以帮助我 先感谢您 代码 public clas
  • 手机重置后AlarmManager闹钟不触发

    在我的应用程序中 用户加入一个计划 然后第二天中午会出现警报通知 这是我的代码 首先 我在 AlarmManager 中设置一个闹钟 如下所示 set alarm to the next day 12 00 noon of the join
  • 如何在 Jetpack compose 中制作 FlipCard 动画

    我有一个现有的应用程序 我在其中使用 XML 中的 Objectanimator 实现了 FlipCard 动画 如下所示 如果我点击一张卡片 它会水平翻转 但现在我想将其迁移到 jetpack compose 那么jetpack comp
  • android.view.InflateException:二进制 XML 文件行 #11:膨胀类 ImageView 时出错

    我只是尝试制作一个小的 android java xml 应用程序来计算游戏的分数 它给了我这个错误 Error inflateing class ImageView 有人知道解决方案吗 我实际上搜索了 ppl 说添加这个 android
  • AltBeacon 服务位于单独的 Android 进程中

    我需要帮助 有一个适用于 Xamarin Android 的应用程序 在其中 启动了一个与 AltBeacon 库配合使用的服务 在此服务中 创建了一个线程 在该线程中不断扫描信标 服务以 StartForeground 启动 该服务应该有
  • Android Studio 安装失败,APK 未签名

    最近从 Eclipse 更改为 Android Studio 我还更改了 JDKjava open jdk to jdk1 7 0 45 现在我尝试运行我的第一个应用程序 并收到以下消息 Installation failed since
  • org.apache.http.conn.HttpHostConnectException:在 android 中连接到 http://localhost 被拒绝

    我正在制作一个应用程序 在执行它时将图像上传到服务器并将其数据库更新到android中的服务器 它显示错误 Connection to http localhost refused 还有更多错误 我研究了这个问题 发现不是提供 URL 连接
  • Android WebView文件上传

    我正在开发一个 Android 应用程序 基本上它是一个WebView和一个进度条 Facebook 的移动网站 m facebook com 已加载到WebView 当我单击 选择文件 按钮上传图像时 没有任何反应 我已经尝试了所有的解决
  • 从 Android 访问云存储

    我一直无法找到任何有关如何从 Android 应用程序使用云存储的具体文档 我确实遇到过这个客户端库 https cloud google com storage docs reference libraries然而 Google Clou
  • 如何使用共享首选项在两个 Android 应用程序之间共享数据?

    我有两个应用程序 App1 和 App2 我想使用共享首选项在 App1 中保存数据并在 App2 中访问 反之亦然 我可以在 App1 中保存数据并在 App2 中访问数据 但反之则不行 这就是我现在正在做的 在清单中 android s
  • phonegap html5 android 同步文件系统 IO

    如何使用 PhoneGaps 文件系统 API 同步读写文件 有可用的同步包装器吗 无法通过提供的 api 同步访问文件 从phonegap的实现方式猜测 我怀疑您是否可以编写一个插件来同步执行此操作
  • Android OptionsMenu问题,背景始终透明

    我的选项菜单总是不显示背景 背景是透明的 有谁知道如何摆脱这个 我的失败起源活动是从另一个自定义活动扩展的 我在 eclipse 上有这个项目 选项菜单工作正常 但自从我迁移到 AndroidStudio 后 选项菜单始终是透明的 我尝试更
  • 可用屏幕的尺寸

    我使用的是 Nexus 7 1280x800 android 4 2 2 API 17 我想获取屏幕的大小 将其划分为相同高度和宽度的正方形部分 我正在使用 FrameLayout 我的方块是 ImageView 的子类 我这样做 cont
  • Android项目中使用java获取电脑的IP地址

    我在用ksoap2 android http code google com p ksoap2 android 我需要使用java获取IP地址 这样我就不必每次都手动输入它 我所说的 IP 地址是指 例如 如果我这样做ipconfig使用命
  • Android Jetpack Compose 尺寸随持续时间变化的动画

    如何在 Jetpack Compose 中添加内容大小更改动画的持续时间 尝试使用Modifier animateContentSize 并通过动画规格具有持续时间 但它只是突然进入或退出 没有观察到持续时间 Column Modifier
  • 按“重置应用程序首选项”后,我的应用程序的所有权限都被撤销

    我开发了一个应用程序 支持Android 6 0 当我在 设置 gt 应用程序 gt 重置应用程序首选项 中重置应用程序首选项时 我的应用程序的所有权限都将被撤销 并且应用程序不会重新启动 撤销权限后未能重新启动应用程序可能会导致许多意外崩

随机推荐