cuốn sách gpt4 ai đã làm

android - 如何使用 CameraSource 拍照?

In lại Tác giả: Vũ trụ không gian Thời gian cập nhật: 2023-11-03 12:27:42 26 4
mua khóa gpt4 Nike

Tôi gặp một số vấn đề với CameraSource khi tôi muốn chụp ảnh bằng máy ảnh của mình. Tất cả những gì tôi muốn là chụp ảnh bằng nút tôi đã tạo trên tệp xml và chụp ảnh bằng "CameraSource" vì tôi cũng đang sử dụng "TextRecognizer". Máy ảnh hoạt động tốt nhưng có vấn đề xảy ra khi tôi nhấn nút chụp ảnh.

tập tin danh sách:




Các biến của tôi:

Camera SurfaceViewXem;
TextView textView;
CameraSource camera_source;
int cuối cùng requestCameraPermissionID = 1001;

类:

// Khởi động CameraSource. Chức năng này sẽ hoạt động.
khoảng trống riêng tư OpenCameraSource(){
TextRecognizer cuối cùng textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!textRecognizer.isOperational()) {
Log.w("Steal_Activity", "Hoạt động của máy dò chưa khả dụng");
Toast.makeText(getApplicationContext(),"Hoạt động của trình phát hiện chưa khả dụng",Toast.LENGTH_SHORT).show();
} khác {
camera_source = CameraSource.Builder mới(getApplicationContext(),textRecognizer)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(1280, 1024)
.setRequestedFps(2.0f)
.setAutoFocusEnabled(true)
.xây dựng();
cameraView.getHolder().addCallback(SurfaceHolder.Callback() {
@Ghi đè
public void surfaceCreated(SurfaceHolder surfaceHolder) {
thử {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Steal.this,
new String[]{android.Manifest.permission.CAMERA},
RequestCameraPermissionID);
return;
}
camera_source.start(cameraView.getHolder());
}catch (IOException ex){
ex.printStackTrace();
}
}
@Ghi đè
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
@Ghi đè
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
camera_source.stop();
}
});
textRecognizer.setProcessor(new Detector.Processor() {
// Some Stuff here
}
});
}
}


// This function will be launched when the button is pressed
public void OnClick_TakeShot(View view){
try{//I GET ERROR HERE
camera_source.takePicture(null,pictureCallback);
}catch (Exception ex){
Toast.makeText(getApplicationContext(),"Error:"+ex.toString(),Toast.LENGTH_LONG).show();
}
}

// Callback for 'takePicture'
CameraSource.PictureCallback pictureCallback = new CameraSource.PictureCallback() {
@Ghi đè
public void onPictureTaken(byte[] bytes) {
File file_image = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+"/pics");
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes , 0, bytes .length);
if(bitmap!=null){
if(!file_image.isDirectory()){
file_image.mkdir();
}
file_image=new File(file_image,"mylastpic.jpg");
try{
FileOutputStream fileOutputStream=new FileOutputStream(file_image);
bitmap.compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
}
catch(Exception exception) {
Toast.makeText(getApplicationContext(),"Error saving: "+ exception.toString(),Toast.LENGTH_LONG).show();
}
}
}
};

按下按钮拍照时不工作 nhập mô tả hình ảnh ở đây

câu trả lời hay nhất

尝试使用这种方式(我正在使用 Google Vision 的 OCR 并使用 CameraSource 拍照)Pd:我还没有修复闪光灯按钮......

您必须使用:在您的依赖项中编译“com.google.android.gms:play-services-vision:9.2.1”以获得 OCR 兼容性

public class CustomCamaraActivity extends BaseActivity implements Callback,
OnClickListener {

bối cảnh bối cảnh riêng tư;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private Camera camera;
private Button flipCamera;
private Button flashCameraButton;
private Button captureImage;
private Button BtnCapturarFoto;
private int cameraId;
private boolean flashmode = false;
private int rotation;
private ActionBar actionBar;
private CameraSource cameraSource;
private StringBuilder builder;
private TextView txTextoCapturado;


private static CustomCamaraActivity instance;
hoạt động hoạt động cá nhân;
private String nombreProyecto;
public static final int REQUEST_IMAGE_CAPTURE = 0020;
private File file;
private String ubicacion;
private static final String TAG = "FOTOGRAFIA";
private int Height = 620, Width = 480;
private TextRecognizer recognizer;

@Ghi đè
khoảng trống được bảo vệ trênCreate(Gói đã lưuInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_camara_layout);
context = this;
// camera surface view created
cameraId = CameraInfo.CAMERA_FACING_BACK;
flipCamera = (Button) findViewById(R.id.flipCamera);
flashCameraButton = (Button) findViewById(R.id.flash);
captureImage = (Button) findViewById(R.id.captureImage);
BtnCapturarFoto = (Button) findViewById(R.id.btnCapturarFoto);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
txTextoCapturado = (TextView) findViewById(R.id.tvTextoCapturado);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
flipCamera.setOnClickListener(this);
captureImage.setOnClickListener(this);
flashCameraButton.setOnClickListener(this);
BtnCapturarFoto.setOnClickListener(this);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

/*if (Camera.getNumberOfCameras() > 1) {
flipCamera.setVisibility(View.VISIBLE);
}*/
if (!getBaseContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)) {
flashCameraButton.setVisibility(View.GONE);
flipCamera.setVisibility(View.GONE);
}


recognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (recognizer.isOperational()) {

cameraSource = new CameraSource.Builder(getApplicationContext(), recognizer)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(1280, 1024)
.setRequestedFps(15.0f)
.setAutoFocusEnabled(true)
.xây dựng();

surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
@Ghi đè
public void surfaceCreated(Người giữ SurfaceHolder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(CustomCamaraActivity.this, new String[]{Manifest.permission.CAMERA}, 100);
return;
}
thử {
releaseCamera();
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}

@Ghi đè
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

}

@Ghi đè
public void surfaceDestroyed(Người giữ SurfaceHolder) {
if(cameraSource != null){
cameraSource.stop();
}
}
});
recognizer.setProcessor(new Detector.Processor() {
@Ghi đè
phát hành khoảng trống công khai () {

}

@Ghi đè
public void receiveDetections(Detector.Detections detections) {
final SparseArray items = detections.getDetectedItems();
if (items.size() != 0) {
builder = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
TextBlock it = items.valueAt(i);
builder.append(it.getValue());
}
final String read = builder.toString().trim();
//String read = builder.toString().trim().replace(" ", "").replace("\n", "");
try{
runOnUiThread(new Runnable() {
@Ghi đè
công khai void run() {
txTextoCapturado.setText(read);
}
});
}catch (Exception ex){
Log.e("error","Error al actualizar texto OCR");
}

//It continues doing other things here
}
}
});
}
}

@Ghi đè
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 100:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
thử {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
phá vỡ;
}
}


public String getUbicacion() {
return ubicacion;
}

@Ghi đè
khoảng trống được bảo vệ trênResume() {
super.onResume();
}

@Ghi đè
khoảng trống được bảo vệ onPause() {
super.onPause();
if (camera != null) {
camera.setPreviewCallback(null);
camera.setErrorCallback(null);
camera.stopPreview();
camera.release();
camera = null;
}
}

@Ghi đè
khoảng trống công khai trênBackPressed() {
super.onBackPressed();
if(camera != null){
camera.setPreviewCallback(null);
camera.setErrorCallback(null);
camera.stopPreview();
camera.release();
camera = null;
}
}

@Ghi đè
public void surfaceCreated(Người giữ SurfaceHolder) {
if (!openCamera(CameraInfo.CAMERA_FACING_BACK)) {
alertCameraDialog();
}

}

private boolean openCamera(int id) {
kết quả boolean = sai;
cameraId = id;
//releaseCamera();
thử {
camera = Camera.open(cameraId);
} catch (Exception e) {
e.printStackTrace();
}
if (camera != null) {
thử {
setUpCamera(camera);
camera.setErrorCallback(new ErrorCallback() {

@Ghi đè
public void onError(int error, Camera camera) {

}
});
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
kết quả = đúng;
} catch (IOException e) {
e.printStackTrace();
kết quả = sai;
releaseCamera();
}
}
return result;
}

private void setUpCamera(Camera c) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
xoay = getWindowManager().getDefaultDisplay().getRotation();
int độ = 0;
công tắc (xoay) {
trường hợp Surface.ROTATION_0:
độ = 0;
phá vỡ;
trường hợp Surface.ROTATION_90:
độ = 90;
phá vỡ;
trường hợp Surface.ROTATION_180:
độ = 180;
phá vỡ;
trường hợp Surface.ROTATION_270:
độ = 270;
phá vỡ;

default:
phá vỡ;
}

if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
// mặt trước
xoay = (thông tin.định hướng + độ) % 330;
xoay = (360 - xoay) % 360;
} khác {
// Quay mặt lại
xoay = (thông tin.định hướng - độ + 360)% 360;
}
c.setDisplayOrientation(xoay);
Tham số params = c.getParameters();

showFlashButton(params);

Danh sách focusModes = params.getSupportedFlashModes();
if (focusModes != null) {
if (focusModes
.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
params.setFlashMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
}
}

params.setRotation(xoay);
}

void void showFlashButton(Thông số tham số) {
boolean showFlash = (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH) && params.getFlashMode() != null)
&& params.getSupportedFlashModes() != null
&& params.getSupportedFocusModes().size() > 1;

flashCameraButton.setVisibility(showFlash? View.VISIBLE
: Xem.INVISIBLE);

}

phát hành void riêng tưCamera() {
thử {
if (camera != null) {
camera.setPreviewCallback(null);
camera.setErrorCallback(null);
camera.stopPreview();
camera.release();
camera = null;
}
} catch (Exception e) {
e.printStackTrace();
Log.e("lỗi", e.toString());
camera = null;
}
}

phát hành khoảng trống riêng tưCameraSource() {
thử {
if (máy ảnhSource != null) {
cameraSource.stop();
cameraSource.release();
máy ảnhSource = null;
}
} catch (Exception e) {
e.printStackTrace();
Log.e("lỗi", e.toString());
máy ảnhSource = null;
}
}

@Ghi đè
public void surfaceChanged(Giữ SurfaceHolder, định dạng int, chiều rộng int,
chiều cao int) {

}

@Ghi đè
public void surfaceDestroyed(Người giữ SurfaceHolder) {

}

@Ghi đè
khoảng trống công khai trênClick(Xem v) {
chuyển đổi (v.getId()) {
trường hợp R.id.flash:
flashOnButton();
phá vỡ;
trường hợp R.id.flipCamera:
flipCamera();
phá vỡ;
trường hợp R.id.captureImage:
lấyHình ảnh();
phá vỡ;
case R.id.btnCapturarFoto:
lấyHình ảnh();
phá vỡ;

default:
phá vỡ;
}
}

khoảng trống riêng tư takeImage() {
try{
//openCamera(CameraInfo.CAMERA_FACING_BACK);
//releaseCameraSource();
//releaseCamera();
//openCamera(CameraInfo.CAMERA_FACING_BACK);
//setUpCamera(máy ảnh);
// Thread.sleep(1000);
cameraSource.takePicture(null, new CameraSource.PictureCallback() {

Tệp riêng tư imageFile;
@Ghi đè
public void onPictureTaken(byte[] bytes) {
thử {
// chuyển đổi mảng byte thành bitmap
Bitmap đã tải Hình ảnh = null;
Bitmap xoayBitmap = null;
đã tảiImage = BitmapFactory.decodeByteArray(byte, 0,
byte.length);

// xoay hình ảnh
Ma trận xoayMatrix = Ma trận mới();
xoayMatrix.postRotate(xoay);
xoayBitmap = Bitmap.createBitmap(loadedImage, 0, 0,
đã tảiImage.getWidth(), đã tảiImage.getHeight(),
xoayMatrix, sai);
String state = Environment.getExternalStorageState();
Thư mục tệp = null;
if (state.contains(Environment.MEDIA_MOUNTED)) {
thư mục = Tệp mới (Môi trường
.getExternalStorageDirectory() + "/Demo");
} khác {
thư mục = Tệp mới (Môi trường
.getExternalStorageDirectory() + "/Demo");
}

thành công boolean = đúng;
if (!folder.exists()) {
thành công = folder.mkdirs();
}
nếu (thành công) {
java.util.Date date = new java.util.Date();
imageFile = Tệp mới (folder.getAbsolutePath()
+ File.separator
//+ Dấu thời gian mới(date.getTime()).toString()
+ "Image.jpg");

imageFile.createNewFile();
} khác {
Toast.makeText(getBaseContext(), "Hình ảnh chưa được lưu",
Toast.LENGTH_SHORT).show();
return;
}

ByteArrayOutputStream ostream = new ByteArrayOutputStream();

// lưu ảnh vào thư viện
xoayBitmap = thay đổi kích thước (rotatedBitmap, 800, 600);
xoayBitmap.compress(CompressFormat.JPEG, 100, ostream);

FileOutputStream fout = new FileOutputStream(imageFile);
fout.write(ostream.toByteArray());
fout.close();
Giá trị ContentValues ​​​​= new ContentValues();

value.put(Hình ảnh.Media.DATE_TAKEN,
System.currentTimeMillis());
value.put(Images.Media.MIME_TYPE, "image/jpeg");
value.put(MediaStore.MediaColumns.DATA,
imageFile.getAbsolutePath());

CustomCamaraActivity.this.getContentResolver().insert(
Hình ảnh.Media.EXTERNAL_CONTENT_URI, giá trị);

setResult(Activity.RESULT_OK); //thêm cái này
hoàn thành();
} catch (Exception e) {
e.printStackTrace();
}
}
});

}catch (Exception ex){
txTextoCapturado.setText("Lỗi chụp ảnh!");
}

}

flipCamera riêng tư () {
int id = (CameraId == CameraInfo.CAMERA_FACING_BACK ? CameraInfo.CAMERA_FACING_FRONT
: CameraInfo.CAMERA_FACING_BACK);
if (!openCamera(id)) {
alertCameraDialog();
}
}

cảnh báo khoảng trống riêng tưCameraDialog() {
Hộp thoại AlertDialog.Builder = createAlert(CustomCamaraActivity.this,
"Thông tin camera", "lỗi mở camera");
hộp thoại.setNegativeButton ("OK", DialogInterface mới.OnClickListener() {
@Ghi đè
public void onClick(hộp thoại DialogInterface, int which) {
hộp thoại.cancel();

}
});

hộp thoại.show();
}

Private Builder createAlert(Ngữ cảnh, Tiêu đề chuỗi, Thông báo chuỗi) {

Hộp thoại AlertDialog.Builder = new AlertDialog.Builder(
ContextThemeWrapper mới (ngữ cảnh,
android.R.style.Theme_Holo_Light_Dialog));
hộp thoại.setIcon(R.drawable.ic_launcher);
nếu (tiêu đề != null)
hộp thoại.setTitle(tiêu đề);
khác
hộp thoại.setTitle("Thông tin");
hộp thoại.setMessage(tin nhắn);
hộp thoại.setCancelable(false);
hộp thoại quay lại;

}

khoảng trống riêng tư flashOnButton() {
if (camera != null) {
thử {
Tham số param = camera.getParameters();
nếu (chế độ flash) {
param.setFlashMode(Parameters.FLASH_MODE_OFF);
flashCameraButton.setBackground(getResources().getDrawable(R.drawable.ic_flash_off));
} khác {
param.setFlashMode(Parameters.FLASH_MODE_TORCH);
flashCameraButton.setBackground(getResources().getDrawable(R.drawable.ic_flash_on));
}
//param.setFlashMode(!flashmode ? Parameters.FLASH_MODE_TORCH : Parameters.FLASH_MODE_OFF);
camera.setParameter(param);
flashmode = !flashmode;
} catch (Exception e) {
e.printStackTrace();
// TODO: xử lý ngoại lệ
}

}
}

/**
*Phương pháp để cải thiện hình ảnh bằng cách xác định trước độ phân giải.
*
* Hình ảnh @param
* @param maxWidth
* @param maxHeight
* @trở lại
*/
Thay đổi kích thước Bitmap riêng tư (Hình ảnh Bitmap, int maxWidth, int maxHeight) {
if (maxHeight > 0 && maxWidth > 0) {
int width = image.getWidth();
int chiều cao = image.getHeight();
tỷ lệ floatBitmap = (float) chiều rộng / (float) chiều cao;
tỷ lệ floatMax = (float) maxWidth / (float) maxHeight;

int FinalWidth = maxWidth;
int FinalHeight = maxHeight;
nếu (tỷ lệMax > 1) {
FinalWidth = (int) ((float) maxHeight * rateBitmap);
} khác {
FinalHeight = (int) ((float) maxWidth / rateBitmap);
}
hình ảnh = Bitmap.createScaledBitmap(image, FinalWidth, FinalHeight, true);
return image;
} khác {
return image;
}
}

Đây là cách bố trí:


xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<>
android:id="@+id/surfaceView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />


android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="dọc"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">


android:id="@+id/tvTextoCapturado"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:trọng lực="trung tâm"
android:textAlignment="center"
android:textColor="@color/white"
android:textSize="18sp"
android:textStyle="bold" />



android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="10dp"
android:độ cao="0dp"
android:orientation="ngang"
android:weightSum="30">

<>
android:id="@+id/flash"
android:layout_width="60dp"
android:layout_height="40dp"
android:layout_alignBaseline="@+id/captureImage"
android:layout_alignBottom="@+id/captureImage"
android:layout_marginLeft="27dp"
android:layout_marginRight="27dp"
android:layout_toLeftOf="@+id/captureImage"
android:layout_toStartOf="@+id/captureImage"
android:layout_weight="4"
android:background="@drawable/ic_flash_off"
android:trọng lực="trung tâm" />

<>
android:id="@+id/captureImage"
android:layout_width="35dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginLeft="27dp"
android:layout_marginRight="27dp"
android:layout_weight="10"
android:background="@android:drawable/ic_menu_máy ảnh"
android:visibility="gone" />

<>
android:id="@+id/btnCapturarFoto"
style="@style/blue_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="27dp"
android:layout_marginRight="27dp"
android:layout_weight="20"
android:độ cao="0dp"
android:text="Hình ảnh của Tomar" />

<>
android:id="@+id/flipCamera"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_marginLeft="27dp"
android:layout_marginRight="27dp"
android:layout_toRightOf="@id/captureImage"
android:layout_weight="4"
android:background="@drawable/ic_rotate"
android:visibility="vô hình" />


Giới thiệu về android - Làm cách nào để sử dụng CameraSource để chụp ảnh? , chúng tôi đã tìm thấy một câu hỏi tương tự trên Stack Overflow: https://stackoverflow.com/questions/45225887/

26 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress