我想编写一个模块,单击按钮即可打开相机,然后单击并捕获图像。如果我不喜欢该图像,则可以将其删除并再单击一个图像,然后选择该图像,它应返回并在活动中显示该图像。 问题出在我拍照时,相机应用程序崩溃了;当我从图库中拍照时,图片没有显示在图像视图中。
这是我写的脚本:
public class MainpageActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
final int TAKE_PICTURE = 1;
final int ACTIVITY_SELECT_IMAGE = 2;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainpage);
Toolbar toolbar = findViewById(R.id.toolbar);
imageView = (ImageView)this.findViewById(R.id.imageView1);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_camera_alt_black_24dp);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{ RxPermissions rxPermissions = new RxPermissions(MainpageActivity.this);
rxPermissions
.request(Manifest.permission.CAMERA) // ask single or multiple permission once
.subscribe(granted -> {
if (granted) {
selectImage();
} else {
Toast.makeText(MainpageActivity.this, "Permission of camera is denied", Toast.LENGTH_SHORT).show();
}
});
}
});
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
// String temp = null;
File file = new File(extStorageDirectory, "temp.png");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, "temp.png");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainpageActivity.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);
imageView.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);
imageView.setBackgroundDrawable(drawable);
}
}
}
}
答案 0 :(得分:0)
我认为您应该尝试添加此“ android:required =“ true”。
<uses-feature android:name="android.hardware.camera"
android:required="true" />
答案 1 :(得分:0)
@Uma:请按照以下步骤操作,并更改您的代码。
步骤1-在 AndroidManifest.xml
中添加两行<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
并在清单文件的应用程序标记中添加此属性:
android:largeHeap="true"
android:hardwareAccelerated="false"
步骤-2-将lib导入到 build.gradle 文件
中implementation 'com.karumi:dexter:4.2.0' // for handling runtime permissions
步骤-3-在您的 MainpageActivity.java
中@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
this.fab = (FloatingActionButton) this.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
CheckPermission();
}
});
}
private void CheckPermission(){
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
selectImage();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// permission is denied permenantly, navigate user to app settings
}
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
})
.onSameThread()
.check();
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
// String temp = null;
File file = new File(extStorageDirectory, "temp.png");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, "temp.png");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
@SuppressLint("LongLogTag")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}}
希望它对您有帮助。
答案 2 :(得分:0)
首先,您需要获得权限处理
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
此后,您可以使用此按钮来打开图库
//opening image chooser option
choose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
}
});
借助此功能,您可以在UI上显示图像
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//getting image from gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting image to ImageView
image.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
此外,您可以将图像转换为bitmap64:
//converting image to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
byte[] imageBytes = baos.toByteArray();
final String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);