gpt4 book ai didi

java - Camera 2 Api Error - 不拍照的错误

转载 作者:行者123 更新时间:2023-12-01 16:20:20 25 4
gpt4 key购买 nike

我的 Camera 2 Api 遇到问题。

当我尝试拍照时,它不起作用。系统不会崩溃。仅当我尝试拍照时才会出现该错误。

此外,我在另一个 Activity 中获取了所需的所有权限。

出现以下错误。

      Access denied finding property "persist.vendor.camera.privapp.list"

不知道和错误有没有关系。请作为引用。

我知道有类似的问题,但都没有解决。

我删除了一些代码。如果您有任何不便,请告诉我。

提前谢谢您。

public class Camera extends AppCompatActivity implements TextureView.SurfaceTextureListener, 
ActivityCompat.OnRequestPermissionsResultCallback {

private AutoFitTextureView mTextureView;
private static final int REQUEST_CAMERA_PERMISSION = 1;
private static final int REQUEST_WRITE_STORAGE = 2;
private static final int REQUEST_SAVE_IMAGE = 1002;

private static final int MAX_PREVIEW_WIDTH = 2220;
private static final int MAX_PREVIEW_HEIGHT = 1080;
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
private Semaphore mCameraOpenCloseLock = new Semaphore(1);
private String mCameraId;
private CameraDevice mCameraDevice;
private CameraCaptureSession mCaptureSession;
private CaptureRequest.Builder mPreviewRequestBuilder;
private CaptureRequest mPreviewRequest;
private int mSensorOrientation;
private ImageReader mImageReader;
private Size mPreviewSize;
private File mImageFolder;
private Byte bytes;
private Bitmap bitmap;
private File mFile;



protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextureView = (AutoFitTextureView) findViewById(R.id.texture);
Button button02 = (Button)findViewById(R.id.button_take_picture);
button02.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick (View view){
takePicture();
}
}
);
}

}
private void setUpCameraOutputs ( int width, int height){
Activity activity = this;
CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
for (String cameraId : manager.getCameraIdList()) {
CameraCharacteristics characteristics
= manager.getCameraCharacteristics(cameraId);

Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
continue;
}

mCameraId = cameraId;

StreamConfigurationMap map = characteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map == null) {
continue;
}

Size largest = Collections.max(
Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
new CompareSizesByArea());

int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
boolean swappedDimensions = false;
switch (displayRotation) {
case Surface.ROTATION_0:
case Surface.ROTATION_180:
if (mSensorOrientation == 90 || mSensorOrientation == 270) {
swappedDimensions = true;
}
break;
case Surface.ROTATION_90:
case Surface.ROTATION_270:
if (mSensorOrientation == 0 || mSensorOrientation == 180) {
swappedDimensions = true;
}
break;
}

Point displaySize = new Point();
activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
int rotatedPreviewWidth = width;
int rotatedPreviewHeight = height;
int maxPreviewWidth = displaySize.x;
int maxPreviewHeight = displaySize.y;

if (swappedDimensions) {
rotatedPreviewWidth = height;
rotatedPreviewHeight = width;
maxPreviewWidth = displaySize.y;
maxPreviewHeight = displaySize.x;
}

if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
maxPreviewWidth = MAX_PREVIEW_WIDTH;
}

if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
maxPreviewHeight = MAX_PREVIEW_HEIGHT;
}

mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
maxPreviewHeight, largest);

int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
mTextureView.setAspectRatio(
mPreviewSize.getWidth(), mPreviewSize.getHeight());
} else {
mTextureView.setAspectRatio(
mPreviewSize.getHeight(), mPreviewSize.getWidth());
}

return;
}
} catch (CameraAccessException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
}

protected void takePicture () {
if (null == mCameraDevice) {
Log.e("Camera", "cameraDevice is null");
return;
}

if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
return;
}else{
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(this,"We need your permission to record and save image",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE_STORAGE);
}

CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

try {
CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraDevice.getId());
Size[] jpegSizes = null;
if (characteristics != null) {
jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
}
int width = 640;
int height = 480;
if (jpegSizes != null && 0 < jpegSizes.length) {
width = jpegSizes[0].getWidth();
height = jpegSizes[0].getHeight();
}
final ImageReader mImageReader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 2);
List<Surface> outputSurfaces = new ArrayList<>(2);
outputSurfaces.add(mImageReader.getSurface());
outputSurfaces.add(new Surface(mTextureView.getSurfaceTexture()));

int rotation = getWindowManager().getDefaultDisplay().getRotation();

//Callback that is called when a new image is available from ImageReader
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {

@Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
//try {
mFile = new File(getExternalFilesDir(null), "sample.jpg");

ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(mFile);
fileOutputStream.write(bytes);
} catch (Exception e) {
e.printStackTrace();
}finally {
mImageReader.close();
if (null != fileOutputStream){
try {
fileOutputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
}

}

};


mImageReader.setOnImageAvailableListener(readerListener, null);
final CameraCaptureSession.CaptureCallback captureListener =
new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
Toast.makeText(Camera.this, "Saved:" + mImageReader, Toast.LENGTH_SHORT).show();

createCameraPreviewSession();

}
};
mCameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(CameraCaptureSession session) {
try {
session.capture(mPreviewRequestBuilder.build(), captureListener, null);

} catch (CameraAccessException e) {
e.printStackTrace();
}
}

@Override
public void onConfigureFailed(CameraCaptureSession session) {

}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void createCameraPreviewSession () {
try {
SurfaceTexture texture = mTextureView.getSurfaceTexture();
assert texture != null;
Surface surface = new Surface(texture);

mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
mPreviewRequestBuilder.addTarget(surface);
mCameraDevice.createCaptureSession(Arrays.asList(surface),
new CameraCaptureSession.StateCallback() {

@Override
public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
if (null == mCameraDevice) {
return;
}

mCaptureSession = cameraCaptureSession;
try {
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);

mPreviewRequest = mPreviewRequestBuilder.build();
mCaptureSession.setRepeatingRequest(mPreviewRequest,
null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}

@Override
public void onConfigureFailed(
@NonNull CameraCaptureSession cameraCaptureSession) {
}
}, null
);

} catch (CameraAccessException e) {
e.printStackTrace();
}

}


private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {

@Override
public void onOpened(@NonNull CameraDevice cameraDevice) {
mCameraOpenCloseLock.release();
mCameraDevice = cameraDevice;
createCameraPreviewSession();

}

@Override
public void onDisconnected(@NonNull CameraDevice cameraDevice) {
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;

}

@Override
public void onError(@NonNull CameraDevice cameraDevice, int error) {
Log.d("debug","Camera error");
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;

}

};

@RequiresApi(api = Build.VERSION_CODES.M)
private void openCamera ( int width, int height){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this,"No permission to open camera",Toast.LENGTH_SHORT).show();
requestPermissions(new String[]{Manifest.permission.CAMERA},REQUEST_CAMERA_PERMISSION);
return;
}

setUpCameraOutputs(width, height);
CameraManager manager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE);
try {
if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Time out waiting to lock camera opening.");
}
manager.openCamera(mCameraId, mStateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
}
}

}

最佳答案

在尝试拍摄实际照片之前,您能否首先尝试请求相机许可?也许这就是它崩溃的原因。

从您的方法“拍照”中删除此权限部分

if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
return;
}else{
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(this,"We need your permission to record and save image",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE_STORAGE);
}

您可以在调用拍照之前先执行它

关于java - Camera 2 Api Error - 不拍照的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62301357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com