AndroidManifest.xml中添加注册
package com.example.mycamera;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
public static final int TAKE_PHOTO = 1;
public static final int CHOOSE_PHOTO = 2;
private ImageView picture;
private Button pestDection = null;
private Button pictureSave = null;
private Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pestDection = super.findViewById(R.id.pestDetection);
pictureSave = super.findViewById(R.id.pictureSave);
picture = findViewById(R.id.picture);
pestDection.setOnClickListener(new pestDectionFuntion());
pictureSave.setOnClickListener(new pictureSaveFunction());
Button chooseFromAlbum = findViewById(R.id.choose_from_album);
chooseFromAlbum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CHOOSE_PHOTO);
} else {
//openAlbum();//打开album的界面
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
startActivityForResult(intent, CHOOSE_PHOTO);//打开相册
}
}
});
Button takePhoto = findViewById(R.id.take_photo);
takePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 创建一个File对象,用于保存摄像头拍下的图片,这里把图片命名为output_image.jpg
// 并将它存放在手机SD卡的应用关联缓存目录下
File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
// 对照片的更换设置
try {
// 如果上一次的照片存在,就删除
if (outputImage.exists()) {
outputImage.delete();
}
// 创建一个新的文件
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
// 如果Android版本大于等于7.0
if (Build.VERSION.SDK_INT >= 24) {
// 将File对象转换成一个封装过的Uri对象
imageUri = FileProvider.getUriForFile(MainActivity.this, "com.example.lenovo.cameraalbumtest.fileprovider", outputImage);
Log.d("MainActivity", outputImage.toString() + "手机系统版本高于Android7.0");
} else {
// 将File对象转换为Uri对象,这个Uri标识着output_image.jpg这张图片的本地真实路径
Log.d("MainActivity", outputImage.toString() + "手机系统版本低于Android7.0");
imageUri = Uri.fromFile(outputImage);
}
// 动态申请权限
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, TAKE_PHOTO);
} else {
// 启动相机程序
Intent intent4 = new Intent("android.media.action.IMAGE_CAPTURE");
// 指定图片的输出地址为imageUri
intent4.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent4, TAKE_PHOTO);
}
}
});
}
private class pestDectionFuntion implements View.OnClickListener {
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "粮虫检测", Toast.LENGTH_SHORT).show();
}
}
private class pictureSaveFunction implements View.OnClickListener {
public void onClick(View view) {
BitmapDrawable bmpDrawable = (BitmapDrawable) picture.getDrawable();
Bitmap bitmap = bmpDrawable.getBitmap();
saveToSystemGallery(bitmap);//将图片保存到本地
Toast.makeText(getApplicationContext(), "图片保存成功!", Toast.LENGTH_SHORT).show();
}
}
@TargetApi(19)
private void handleImageOnKitkat(Intent data) {
String imagePath = null;
Uri uri = data.getData();
if (DocumentsContract.isDocumentUri(this, uri)) {
//如果是document类型的uri,则通过document id处理
String docId = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
String id = docId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=" + id;
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content:" +
"//downloads/public_downloads"), Long.valueOf(docId));
imagePath = getImagePath(contentUri, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
//如果是content类型的uri,则使用普通方式处理
imagePath = getImagePath(uri, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
//如果是File类型的uri,直接获取图片路径即可
imagePath = uri.getPath();
}
//根据图片路径显示图片
displayImage(imagePath);
}
private void handleImageBeforeKitKat(Intent data) {
Uri uri = data.getData();
String imagePath = getImagePath(uri, null);
displayImage(imagePath);
}
public void saveToSystemGallery(Bitmap bmp) {
// 首先保存图片
File appDir = new File(Environment.getExternalStorageDirectory(), "MyAlbums");
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 其次把文件插入到系统图库
//sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(file.getAbsolutePath())));
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(file);
intent.setData(uri);
sendBroadcast(intent); // 发送广播,通知图库更新
}
// 使用startActivityForResult()方法开启Intent的回调
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PHOTO:
if (requestCode == TAKE_PHOTO && resultCode == RESULT_OK) {
try {
// 将图片解析成Bitmap对象
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
break;
case CHOOSE_PHOTO:
//返回成功,请求码(对应启动时的requestCode)
if (resultCode == RESULT_OK && CHOOSE_PHOTO == 2) {
//下把图片显示在ImageView中
Uri uri = data.getData();
ContentResolver cr = this.getContentResolver();
try {
//根据Uri获取流文件
InputStream is = cr.openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 3;
Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
picture.setImageBitmap(bitmap);
} catch (Exception e) {
Log.i("lyf", e.toString());
}
}
super.onActivityResult(requestCode, resultCode, data);
break;
default:
break;
}
}
private String getImagePath(Uri uri, String selection) {
String path = null;
Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
private void displayImage(String imagePath) {
if (imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
picture.setImageBitmap(bitmap);//将图片放置在控件上
} else {
Toast.makeText(this, "得到图片失败", Toast.LENGTH_SHORT).show();
}
}
}
activity_main.xml代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/take_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:drawable/ic_menu_camera"
android:text="" />
<Button
android:id="@+id/choose_from_album"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_toRightOf="@+id/take_photo"
android:background="@android:drawable/ic_menu_gallery"
android:text="" />
<Button
android:id="@+id/pestDetection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="9dp"
android:layout_toRightOf="@+id/choose_from_album"
android:background="@android:drawable/ic_menu_zoom"
android:text="" />
<Button
android:id="@+id/pictureSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="9dp"
android:layout_toRightOf="@+id/pestDetection"
android:background="@android:drawable/ic_menu_save" />
<ImageView
android:id="@+id/picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/choose_from_album"
android:layout_marginTop="54dp"
android:background="@drawable/logo"
android:gravity="center_horizontal"
android:scaleType="center" />
</RelativeLayout>
file_path.xml代码
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="my_images"
path="." />
</paths>
总结
去掉了页面间的跳转,更简洁紧凑。
https://wwzb.lanzoue.com/iCmzw0n2rcch
密码:8238
分享Demo可试试效果