我想写一个模块,在点击一个按钮,相机打开,我可以点击和捕捉图像。如果我不喜欢图像,我可以删除它,然后点击另一个图像,然后选择图像,它应该返回并在活动中显示该图像。
当前回答
你可以使用此代码onClick监听器(你可以使用ImageView或按钮)
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, 1);
}
}
});
在imageView中显示
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
bitmap = (Bitmap) extras.get("data");
image.setImageBitmap(bitmap);
}
}
注意:将此插入舱单
<uses-feature android:name="android.hardware.camera" android:required="true" />
其他回答
请使用Kotlin和Andoirdx支持来实现这个例子:
button1.setOnClickListener{
file = getPhotoFile()
val uri: Uri = FileProvider.getUriForFile(applicationContext, "com.example.foto_2.filrprovider", file!!)
captureImage.putExtra(MediaStore.EXTRA_OUTPUT, uri)
val camaraActivities: List<ResolveInfo> = applicationContext.getPackageManager().queryIntentActivities(captureImage, PackageManager.MATCH_DEFAULT_ONLY)
for (activity in camaraActivities) {
applicationContext.grantUriPermission(activity.activityInfo.packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
}
startActivityForResult(captureImage, REQUEST_PHOTO)
}
活动结果:
if (requestCode == REQUEST_PHOTO) {
val uri = FileProvider.getUriForFile(applicationContext, "com.example.foto_2.filrprovider", file!!)
applicationContext.revokeUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
imageView1.viewTreeObserver.addOnGlobalLayoutListener {
width = imageView1.width
height = imageView1.height
imageView1.setImageBitmap(getScaleBitmap(file!!.path , width , height))
}
if(width!=0&&height!=0){
imageView1.setImageBitmap(getScaleBitmap(file!!.path , width , height))
}else{
val size = Point()
this.windowManager.defaultDisplay.getSize(size)
imageView1.setImageBitmap(getScaleBitmap(file!!.path , size.x , size.y))
}
}
您可以在https://github.com/joelmmx/take_photo_kotlin.git上获得更多详细信息
我希望它能帮助你!
坏的质量
根据我的经验,如果我们使用
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, RESULT_ADD_PHOTO);
和处理onActivityResult()
Bitmap thumbnail= (Bitmap) data.getExtras().get("data");
它只会给你一个缩略图,当然有一个坏的质量。
不错的质量
您可以显示相机和保存您的图像文件在公共目录,例如在文档目录
在onClick()中使用这个
String imagePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) +
File.separator + "your_image_name.jpeg";
Intent i =new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageFile = new File(imagePath );
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
startActivityForResult(i, RESULT_ADD_PHOTO);
在onActivityResult()中
Bitmap imageBitmap1 = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap imageBitmap = Bitmap.createBitmap(imageBitmap1, 0, 0, imageBitmap1.getWidth(), imageBitmap1.getHeight(), matrix, true);
binding.imageView.setImageBitmap(imageBitmap);
我使用postRotate(),因为在我的代码中,图像结果向左旋转,所以我需要将其旋转90
更新(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。
您可以使用自定义相机与缩略图图像。 你可以看看我的项目。
从相机捕获照片+从图库中选择图像,并将其设置为布局或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"/>
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在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)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?