Android开发 拍照+读取相册+保存到本地(单页面版)

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可试试效果

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Unity中,你可以使用AndroidJava API来读取本地图片。以下是一个简的示例: 1. 首先,创建一个C#脚本,用于调用Java API: ```csharp using UnityEngine; using System.Collections; public class AndroidGallery : MonoBehaviour { private AndroidJavaObject galleryActivity; void Start () { // 获取GalleryActivity类的引用 galleryActivity = new AndroidJavaObject("com.example.gallery.GalleryActivity"); } public void OpenGallery() { // 调用GalleryActivity类中的OpenGallery方法 galleryActivity.Call("OpenGallery"); } public void SetImage(string path) { // 调用GalleryActivity类中的SetImage方法 galleryActivity.Call("SetImage", path); } } ``` 2. 然后,在Android项目中创建一个名为GalleryActivity的Java类: ```java package com.example.gallery; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; public class GalleryActivity extends Activity { private static final int SELECT_PICTURE = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public void OpenGallery() { Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*"); startActivityForResult(intent, SELECT_PICTURE); } public void SetImage(String path) { // 在Unity中调用SetImage方法时,将图片路径传递给该方法 Intent intent = new Intent(); intent.setData(Uri.parse(path)); setResult(Activity.RESULT_OK, intent); finish(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK) { String path = data.getDataString(); // 将图片路径返回给Unity SetImage(path); } } } ``` 3. 最后,在Unity中使用AndroidGallery脚本来加载本地图片: ```csharp using UnityEngine; using UnityEngine.UI; using System.Collections; public class LoadImage : MonoBehaviour { public RawImage image; void Start () { // 创建AndroidGallery对象 AndroidGallery androidGallery = new AndroidGallery(); // 在Android设备上打开相册 androidGallery.OpenGallery(); } void Update () { // 检查是否有新的图片被选择 if (Input.GetKeyDown(KeyCode.Escape)) { string path = PlayerPrefs.GetString("ImagePath"); if (path != "") { // 加载本地图片 StartCoroutine(LoadLocalImage(path)); } } } IEnumerator LoadLocalImage(string path) { WWW www = new WWW("file://" + path); yield return www; // 将加载的图片显示在RawImage组件中 image.texture = www.texture; } } ``` 在上面的示例中,我们通过AndroidGallery脚本打开了Android设备上的相册,然后在GalleryActivity类中选择了一张图片,并将其路径传递给了Unity。在Unity中,我们使用PlayerPrefs来存储图片路径,并使用WWW类来加载本地图片。最后,我们将加载的图片显示在RawImage组件中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值