我想写一个模块,在点击一个按钮,相机打开,我可以点击和捕捉图像。如果我不喜欢图像,我可以删除它,然后点击另一个图像,然后选择图像,它应该返回并在活动中显示该图像。
当前回答
正如其他人所讨论的,使用data. getextras ().get("data")只会得到低质量的缩略图。
解决方案是通过ACTION_IMAGE_CAPTURE意图传递一个位置,告诉相机在哪里存储全质量图像。
代码是Kotlin,不需要任何权限。
val f = File("${getExternalFilesDir(null)}/imgShot")
val photoURI = FileProvider.getUriForFile(this, "${packageName}.fileprovider", f)
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
.apply { putExtra(MediaStore.EXTRA_OUTPUT, photoURI) }
startActivityForResult(intent, 1234)
然后对拍摄后的结果进行处理:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == 1234 && resultCode == Activity.RESULT_OK) {
val bitmap = BitmapFactory.decodeFile(
File("${getExternalFilesDir(null)}/imgShot").toString()
)
// use imageView.setImageBitmap(bitmap) or whatever
}
}
您还需要像这里描述的那样添加一个外部FileProvider。AndroidManifest.xml:
<manifest>
<application>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provide_paths" />
</provider>
</application>
</manifest>
添加一个新文件app/src/main/res/xml/provide_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="." />
</paths>
最后,你应该用你自己的逻辑替换1234来跟踪请求代码(通常是一个包含RequestCode.CAPTURE_IMAGE等成员的枚举)
其他回答
以下是完整的代码:
package com.example.cameraa;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
Button btnTackPic;
Uri photoPath;
ImageView ivThumbnailPhoto;
static int TAKE_PICTURE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get reference to views
btnTackPic = (Button) findViewById(R.id.bt1);
ivThumbnailPhoto = (ImageView) findViewById(R.id.imageView1);
btnTackPic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, TAKE_PICTURE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap)intent.getExtras().get("data");
ivThumbnailPhoto.setImageBitmap(photo);
ivThumbnailPhoto.setVisibility(View.VISIBLE);
}
}
}
记住也要为相机添加权限。
你可以使用此代码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" />
下面是一个示例活动,它将启动相机应用程序,然后检索图像并显示它。
package edu.gvsu.cis.masl.camerademo;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MyCameraActivity extends Activity
{
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
}
else
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
else
{
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
@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);
}
}
}
请注意,相机应用程序本身提供了查看/重拍图像的功能,一旦图像被接受,活动就会显示它。
下面是上面的活动使用的布局。它只是一个包含id为button1的Button和id为imageview1的ImageView的LinearLayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/photo"></Button>
<ImageView android:id="@+id/imageView1" android:layout_height="wrap_content" android:src="@drawable/icon" android:layout_width="wrap_content"></ImageView>
</LinearLayout>
最后一个细节,一定要加上:
<uses-feature android:name="android.hardware.camera"></uses-feature>
如果摄像头是你应用功能的可选选项。请确保在权限中将require设置为false。像这样
<uses-feature android:name="android.hardware.camera" android:required="false"></uses-feature>
到你的manifest.xml。
在活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
image = (ImageView) findViewById(R.id.imageButton);
image.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
SimpleDateFormat sdfPic = new SimpleDateFormat(DATE_FORMAT);
currentDateandTime = sdfPic.format(new Date()).replace(" ", "");
File imagesFolder = new File(IMAGE_PATH, currentDateandTime);
imagesFolder.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = IMAGE_NAME + n + IMAGE_FORMAT;
File file = new File(imagesFolder, fname);
outputFileUri = Uri.fromFile(file);
cameraIntent= new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CAMERA_DATA);
}catch(Exception e) {
e.printStackTrace();
}
}
});
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case CAMERA_DATA :
final int IMAGE_MAX_SIZE = 300;
try {
// Bitmap bitmap;
File file = null;
FileInputStream fis;
BitmapFactory.Options opts;
int resizeScale;
Bitmap bmp;
file = new File(outputFileUri.getPath());
// This bit determines only the width/height of the
// bitmap
// without loading the contents
opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
fis = new FileInputStream(file);
BitmapFactory.decodeStream(fis, null, opts);
fis.close();
// Find the correct scale value. It should be a power of
// 2
resizeScale = 1;
if (opts.outHeight > IMAGE_MAX_SIZE
|| opts.outWidth > IMAGE_MAX_SIZE) {
resizeScale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE/ (double) Math.max(opts.outHeight, opts.outWidth)) / Math.log(0.5)));
}
// Load pre-scaled bitmap
opts = new BitmapFactory.Options();
opts.inSampleSize = resizeScale;
fis = new FileInputStream(file);
bmp = BitmapFactory.decodeStream(fis, null, opts);
Bitmap getBitmapSize = BitmapFactory.decodeResource(
getResources(), R.drawable.male);
image.setLayoutParams(new RelativeLayout.LayoutParams(
200,200));//(width,height);
image.setImageBitmap(bmp);
image.setRotation(90);
fis.close();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 70, baos);
imageByte = baos.toByteArray();
break;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
在layout.xml:
enter code here
<RelativeLayout
android:id="@+id/relativeLayout2"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/XXXXXXX"
android:textAppearance="?android:attr/textAppearanceSmall" />
在manifest.xml:
< uses-permission android: name = " android.permission。CAMERA" /> <uses-feature android:name="android.硬件。相机" / >
使用下面的代码捕捉图片使用您的移动相机。 如果你使用的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);
}
}
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在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)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?