我想写一个模块,在点击一个按钮,相机打开,我可以点击和捕捉图像。如果我不喜欢图像,我可以删除它,然后点击另一个图像,然后选择图像,它应该返回并在活动中显示该图像。
当前回答
从相机捕获照片+从图库中选择图像,并将其设置为布局或imageview的背景。下面是示例代码。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class Post_activity extends Activity
{
final int TAKE_PICTURE = 1;
final int ACTIVITY_SELECT_IMAGE = 2;
ImageView openCameraOrGalleryBtn,cancelBtn;
LinearLayout backGroundImageLinearLayout;
public void onCreate(Bundle savedBundleInstance) {
super.onCreate(savedBundleInstance);
overridePendingTransition(R.anim.slide_up,0);
setContentView(R.layout.post_activity);
backGroundImageLinearLayout=(LinearLayout)findViewById(R.id.background_image_linear_layout);
cancelBtn=(ImageView)findViewById(R.id.cancel_icon);
openCameraOrGalleryBtn=(ImageView)findViewById(R.id.camera_icon);
openCameraOrGalleryBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
selectImage();
}
});
cancelBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
overridePendingTransition(R.anim.slide_down,0);
finish();
}
});
}
public void selectImage()
{
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Post_activity.this);
builder.setTitle("Add Photo!");
builder.setItems(options,new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(options[which].equals("Take Photo"))
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, TAKE_PICTURE);
}
else if(options[which].equals("Choose from Gallery"))
{
Intent intent=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, ACTIVITY_SELECT_IMAGE);
}
else if(options[which].equals("Cancel"))
{
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestcode,int resultcode,Intent intent)
{
super.onActivityResult(requestcode, resultcode, intent);
if(resultcode==RESULT_OK)
{
if(requestcode==TAKE_PICTURE)
{
Bitmap photo = (Bitmap)intent.getExtras().get("data");
Drawable drawable=new BitmapDrawable(photo);
backGroundImageLinearLayout.setBackgroundDrawable(drawable);
}
else if(requestcode==ACTIVITY_SELECT_IMAGE)
{
Uri selectedImage = intent.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Drawable drawable=new BitmapDrawable(thumbnail);
backGroundImageLinearLayout.setBackgroundDrawable(drawable);
}
}
}
public void onBackPressed() {
super.onBackPressed();
//overridePendingTransition(R.anim.slide_down,0);
}
}
Add these permission in Androidmenifest.xml file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
其他回答
我创建了一个对话框,可以从图库或相机中选择图像。 回调函数为
Uri,如果图像来自图库 字符串作为文件路径,如果图像是从相机捕获。 从相机中选择的图像需要作为多部分文件数据上传到互联网上
首先,我们要在AndroidManifest中定义权限,因为我们需要在创建文件和从画廊读取图像时写入外部存储
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
中创建file_paths xml文件 应用程序/ src / main / res / xml / file_paths.xml
与路径
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
然后我们需要定义文件提供者来生成Content uri来访问存储在外部存储器中的文件
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
河流布局
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.50" />
<ImageView
android:id="@+id/gallery"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginStart="8dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="32dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/guideline2"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/ic_menu_gallery" />
<ImageView
android:id="@+id/camera"
android:layout_width="48dp"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="32dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/ic_menu_camera" />
</androidx.constraintlayout.widget.ConstraintLayout>
ImagePicker Dailog
public class ImagePicker extends BottomSheetDialogFragment {
ImagePicker.GetImage getImage;
public ImagePicker(ImagePicker.GetImage getImage, boolean allowMultiple) {
this.getImage = getImage;
}
File cameraImage;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.bottom_sheet_imagepicker, container, false);
view.findViewById(R.id.camera).setOnClickListener(new View.OnClickListener() {@
Override
public void onClick(View view) {
if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE
}, 2000);
} else {
captureFromCamera();
}
}
});
view.findViewById(R.id.gallery).setOnClickListener(new View.OnClickListener() {@
Override
public void onClick(View view) {
if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE
}, 2000);
} else {
startGallery();
}
}
});
return view;
}
public interface GetImage {
void setGalleryImage(Uri imageUri);
void setCameraImage(String filePath);
void setImageFile(File file);
}@
Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK) {
if(requestCode == 1000) {
Uri returnUri = data.getData();
getImage.setGalleryImage(returnUri);
Bitmap bitmapImage = null;
}
if(requestCode == 1002) {
if(cameraImage != null) {
getImage.setImageFile(cameraImage);
}
getImage.setCameraImage(cameraFilePath);
}
}
}
private void startGallery() {
Intent cameraIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
cameraIntent.setType("image/*");
if(cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(cameraIntent, 1000);
}
}
private String cameraFilePath;
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "Camera");
File image = File.createTempFile(imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ );
cameraFilePath = "file://" + image.getAbsolutePath();
cameraImage = image;
return image;
}
private void captureFromCamera() {
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider", createImageFile()));
startActivityForResult(intent, 1002);
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
像这样调用Activity或fragment 在Fragment/Activity中定义ImagePicker
ImagePicker imagePicker;
然后在点击按钮时调用dailog
imagePicker = new ImagePicker(new ImagePicker.GetImage() {
@Override
public void setGalleryImage(Uri imageUri) {
Log.i("ImageURI", imageUri + "");
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContext().getContentResolver().query(imageUri, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mediaPath = cursor.getString(columnIndex);
// Set the Image in ImageView for Previewing the Media
imagePreview.setImageBitmap(BitmapFactory.decodeFile(mediaPath));
cursor.close();
}
@Override
public void setCameraImage(String filePath) {
mediaPath =filePath;
Glide.with(getContext()).load(filePath).into(imagePreview);
}
@Override
public void setImageFile(File file) {
cameraImage = file;
}
}, true);
imagePicker.show(getActivity().getSupportFragmentManager(), imagePicker.getTag());
使用下面的代码捕捉图片使用您的移动相机。 如果你使用的android版本高于棒棒糖,你也应该添加权限请求。
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
@override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
从相机捕获照片+从图库中选择图像,并将其设置为布局或imageview的背景。下面是示例代码。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class Post_activity extends Activity
{
final int TAKE_PICTURE = 1;
final int ACTIVITY_SELECT_IMAGE = 2;
ImageView openCameraOrGalleryBtn,cancelBtn;
LinearLayout backGroundImageLinearLayout;
public void onCreate(Bundle savedBundleInstance) {
super.onCreate(savedBundleInstance);
overridePendingTransition(R.anim.slide_up,0);
setContentView(R.layout.post_activity);
backGroundImageLinearLayout=(LinearLayout)findViewById(R.id.background_image_linear_layout);
cancelBtn=(ImageView)findViewById(R.id.cancel_icon);
openCameraOrGalleryBtn=(ImageView)findViewById(R.id.camera_icon);
openCameraOrGalleryBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
selectImage();
}
});
cancelBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
overridePendingTransition(R.anim.slide_down,0);
finish();
}
});
}
public void selectImage()
{
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Post_activity.this);
builder.setTitle("Add Photo!");
builder.setItems(options,new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(options[which].equals("Take Photo"))
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, TAKE_PICTURE);
}
else if(options[which].equals("Choose from Gallery"))
{
Intent intent=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, ACTIVITY_SELECT_IMAGE);
}
else if(options[which].equals("Cancel"))
{
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestcode,int resultcode,Intent intent)
{
super.onActivityResult(requestcode, resultcode, intent);
if(resultcode==RESULT_OK)
{
if(requestcode==TAKE_PICTURE)
{
Bitmap photo = (Bitmap)intent.getExtras().get("data");
Drawable drawable=new BitmapDrawable(photo);
backGroundImageLinearLayout.setBackgroundDrawable(drawable);
}
else if(requestcode==ACTIVITY_SELECT_IMAGE)
{
Uri selectedImage = intent.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Drawable drawable=new BitmapDrawable(thumbnail);
backGroundImageLinearLayout.setBackgroundDrawable(drawable);
}
}
}
public void onBackPressed() {
super.onBackPressed();
//overridePendingTransition(R.anim.slide_down,0);
}
}
Add these permission in Androidmenifest.xml file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
更新(2020)
谷歌已经添加了一个新的ActivityResultRegistry API,“让你处理startActivityForResult() + onActivityResult()以及requestPermissions() + onRequestPermissionsResult()流,而无需覆盖你的活动或片段中的方法,通过ActivityResultContract带来了增加的类型安全性,并为测试这些流提供了钩子”。
该API是在androidx中添加的。和androidx.fragment 1.3.0-alpha02。
所以你现在可以这样做:
val takePicture = registerForActivityResult(ActivityResultContracts.TakePicture()) { success: Boolean ->
if (success) {
// The image was saved into the given Uri -> do something with it
}
}
val imageUri: Uri = ...
button.setOnClickListener {
takePicture.launch(imageUri)
}
查看文档了解如何使用新的Activity结果API: https://developer.android.com/training/basics/intents/result#kotlin
有许多内置的activityresultcontract,允许您做不同的事情,如选择联系人,请求权限,拍照或拍摄视频。您可能对ActivityResultContracts感兴趣。拍摄上图。
注意androidx.fragment 1.3.0-alpha04弃用了Fragment上的startActivityForResult() + onActivityResult()和requestPermissions() + onRequestPermissionsResult() api。因此,从现在开始ActivityResultContracts似乎是一种新的做事方式。
原答案(2015)
我花了好几个小时才把它修好。代码几乎是从developer.android.com复制粘贴而来的,只有细微的区别。
在AndroidManifest.xml上请求此权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在你的Activity中,首先定义这个:
static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;
然后在onClick中触发这个Intent:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.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
Log.i(TAG, "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
添加以下支持方法:
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 = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
然后接收结果:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
mImageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
使它工作的是MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath)),这与developer.android.com的代码不同。原始代码给了我一个FileNotFoundException。
我知道这是一个相当老的线程,但所有这些解决方案都没有完成,当用户旋转相机时,不工作在一些设备上,因为onActivityResult中的数据是空的。这是我在很多设备上测试过的解决方案,到目前为止还没有遇到任何问题。
首先在activity中声明Uri变量:
private Uri uriFilePath;
然后创建临时文件夹,用于存储捕获的图像,并通过相机捕获图像:
PackageManager packageManager = getActivity().getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
File mainDirectory = new File(Environment.getExternalStorageDirectory(), "MyFolder/tmp");
if (!mainDirectory.exists())
mainDirectory.mkdirs();
Calendar calendar = Calendar.getInstance();
uriFilePath = Uri.fromFile(new File(mainDirectory, "IMG_" + calendar.getTimeInMillis()));
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriFilePath);
startActivityForResult(intent, 1);
}
这里有一个最重要的事情,你必须保存你的uriFilePath在onSaveInstanceState中,因为如果你不这样做,用户在使用camera时旋转他的设备,你的uri将为null。
@Override
protected void onSaveInstanceState(Bundle outState) {
if (uriFilePath != null)
outState.putString("uri_file_path", uriFilePath.toString());
super.onSaveInstanceState(outState);
}
之后,你应该在onCreate方法中恢复你的uri:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
if (uriFilePath == null && savedInstanceState.getString("uri_file_path") != null) {
uriFilePath = Uri.parse(savedInstanceState.getString("uri_file_path"));
}
}
}
这里是最后一部分,获得你的Uri在onActivityResult:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
String filePath = uriFilePath.getPath(); // Here is path of your captured image, so you can create bitmap from it, etc.
}
}
}
附注:别忘了在你的Manifest中添加Camera和Ext. storage的写入权限。
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在Android中将字符串转换为Uri
- 如何在NestedScrollView内使用RecyclerView ?
- 移动到另一个EditText时,软键盘下一步点击Android
- Android应用中的GridView VS GridLayout
- Activity和FragmentActivity的区别
- 右对齐文本在android TextView
- 权限拒绝:start前台需要android.permission.FOREGROUND_SERVICE
- 如何更改android操作栏的标题和图标
- Android Split字符串
- 让一个链接在安卓浏览器启动我的应用程序?
- 如何在Android工作室的外部库中添加一个jar ?
- GridLayout(不是GridView)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?