java private static final int REQUEST_IMAGE_CAPTURE = 1; private void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); // 处理照片数据 } }这段代码中data是图片的路径吗
时间: 2023-12-06 22:41:50 浏览: 175
不是,data并不是图片的路径。在这段代码中,我们使用了 `startActivityForResult` 方法来启动一个拍照的 Intent,并传入了一个请求码 `REQUEST_IMAGE_CAPTURE`。当拍照完成后,系统会调用 `onActivityResult` 方法,并传入请求码、结果码以及包含了拍摄照片数据的 Intent 对象。我们可以从这个 Intent 对象中获取照片数据,而不是照片的路径。在这个例子中,我们使用了 `getExtras()` 方法获取 Intent 中的 Bundle 对象,然后从这个 Bundle 对象中获取了照片数据。
相关问题
@AfterPermissionGranted(REQUEST_CAMERA_PERMISSION) private void takePicture() { String[] perms = {Manifest.permission.CAMERA}; if (EasyPermissions.hasPermissions(this, perms)) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (intent.resolveActivity(getPackageManager()) != null) { startActivityForResult(intent, REQUEST_IMAGE_CAPTURE); } } else { EasyPermissions.requestPermissions(this, "需要相机权限来拍照", REQUEST_CAMERA_PERMISSION, perms); } }怎么写,写在哪里,如果加上创建文档用来存储照片,怎么写,完整示例
这段代码是一个使用 EasyPermissions 库来请求相机权限,并启动相机拍照的方法。如果您需要在拍照后将照片保存到文件中,可以在 `onActivityResult()` 方法中处理照片数据并保存到指定位置。
完整示例如下:
```java
private static final int REQUEST_CAMERA_PERMISSION = 1;
private static final int REQUEST_IMAGE_CAPTURE = 2;
private String currentPhotoPath;
@AfterPermissionGranted(REQUEST_CAMERA_PERMISSION)
private void takePicture() {
String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (EasyPermissions.hasPermissions(this, perms)) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
}
} else {
EasyPermissions.requestPermissions(this, "需要相机权限来拍照和存储照片", REQUEST_CAMERA_PERMISSION, perms);
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(currentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath, bmOptions);
imageView.setImageBitmap(bitmap);
// Save the bitmap to a file
try {
FileOutputStream out = new FileOutputStream(currentPhotoPath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这个示例中,我们在 `takePicture()` 方法中请求了相机和存储权限,然后创建了一个用于保存照片的文件,并启动相机拍照。在 `onActivityResult()` 方法中,我们获取了拍摄的照片数据,并将其显示在一个 ImageView 中。然后,我们将照片保存到之前创建的文件中。请注意,在 `createImageFile()` 方法中,我们使用了 FileProvider 来获取照片文件的 Uri,以便在 Android N 及以上版本中能够正常使用。
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");File tempFile = new File(Environment.getExternalStorageDirectory() + "/pic", "temp.png");if (!tempFile.getParentFile().exists()) { tempFile.getParentFile().mkdir();}Uri uri = FileProvider.getUriForFile(MainActivity.this, "com.cmiot.demo.fileprovider", tempFile);intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);startActivityForResult(intent, 100);其mainactivity的完整代码
好的,这是一个完整的 MainActivity 代码,包含了使用相机拍摄照片并保存的代码示例:
```java
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CAMERA_PERMISSION = 100;
private static final int REQUEST_IMAGE_CAPTURE = 200;
private ImageView mImageView;
private Uri mPhotoUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = findViewById(R.id.image_view);
findViewById(R.id.btn_take_photo).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 检查相机权限
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
} else {
takePhoto();
}
}
});
}
private void takePhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
File photoFile = createPhotoFile();
if (photoFile != null) {
mPhotoUri = FileProvider.getUriForFile(this,
getApplicationContext().getPackageName() + ".fileprovider",
photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
} else {
Toast.makeText(this, "创建文件失败", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "没有相机应用", Toast.LENGTH_SHORT).show();
}
}
private File createPhotoFile() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault())
.format(new Date());
String fileName = "IMG_" + timeStamp + ".jpg";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if (storageDir != null) {
if (!storageDir.exists()) {
storageDir.mkdirs();
}
return new File(storageDir, fileName);
} else {
return null;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
if (mPhotoUri != null) {
mImageView.setImageURI(mPhotoUri);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
takePhoto();
} else {
Toast.makeText(this, "没有相机权限", Toast.LENGTH_SHORT).show();
}
}
}
}
```
其中,为了兼容 Android 6.0 及以上版本,需要动态申请相机权限。在 `takePhoto` 方法中,创建一个 Intent 对象,并指定 action 为 `MediaStore.ACTION_IMAGE_CAPTURE`,启动系统相机应用。通过创建一个临时文件,将照片保存到文件中。使用 `FileProvider` 获取文件的 Uri,并将 Uri 作为 Extra 值传递给相机应用,以便相机应用将照片保存到指定的文件中。在 `onActivityResult` 方法中,接收照片拍摄完成后返回的结果,并将照片显示在 ImageView 中。
阅读全文