美文网首页
Android Studio 上传文件实例_拍照、相机上传图片

Android Studio 上传文件实例_拍照、相机上传图片

作者: 牧区叔叔 | 来源:发表于2020-09-20 15:18 被阅读0次

    这是拍照反图片以及相机反图片的简单实例

    小白上路先实现效果再谈原理~

    这里我就先不写思路了,直接上效果图,哪里不懂的留言即可。

    效果

    image.png

    步骤1、权限(清单文件添加)

     <!--拍照-->
        <uses-permission android:name="android.permission.CAMERA" />
        <!--读写-->
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.PERMISSIONS_STORAGE"/>
    

    步骤2、res文件夹下边创建xml文件file_paths.xml命名

    <paths xmlns:android="http://schemas.android.com/apk/res/android">
        <!--files-path  相当于 getFilesDir()-->
        <files-path name="my_images" path="images"/>
        <!--cache-path  相当于 getCacheDir()-->
        <cache-path name="lalala" path="cache_image"/>
        <!--external-path  相当于 Environment.getExternalStorageDirectory()-->
        <external-path name="hahaha" path="comeOn"/>
        <!--external-files-path  相当于 getExternalFilesDir("") -->
        <external-files-path name="paly" path="freeSoft"/>
        <!--external-cache-path  相当于 getExternalCacheDir() -->
        <external-cache-path  name="lei" path="."/>
    </paths>
    

    步骤3、配置清单文件

     <provider
                android:name="androidx.core.content.FileProvider"
                android:authorities="com.mooc.uploadfile4.fileprovider"
                android:exported="false"
                android:grantUriPermissions="true"
                tools:ignore="MissingClass">
                <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/file_paths" />
            </provider>
    
    image.png

    步骤4、布局

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">
    
        <Button
            android:id="@+id/camera_bt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="相机" />
    
        <Button
            android:id="@+id/photo_bt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="相册" />
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:gravity="center"
            android:text="以下是展示相机拍照返回的图片" />
    
        <ImageView
            android:id="@+id/camere_iv"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_marginTop="6dp" />
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:gravity="center"
            android:text="以下是展示相册拍照返回的图片" />
    
        <ImageView
            android:id="@+id/photo_iv"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_marginTop="6dp" />
    
    </LinearLayout>
    
    image.png

    步骤5、MainActivity代码

    package com.mooc.uploadfile4;
    
    import android.Manifest;
    import android.app.Activity;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.net.Uri;
    import android.os.Build;
    import android.os.Bundle;
    import android.os.StrictMode;
    import android.provider.MediaStore;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;
    
    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.core.app.ActivityCompat;
    import androidx.core.content.FileProvider;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    public class MainActivity extends AppCompatActivity {
    
        private Button cameraBt;
        private Button photoBt;
        private ImageView camereIv;
        private ImageView photoIv;
        private String TAG = "tag";
        //需要的权限数组 读/写/相机
        private static String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA};
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            //跳转相机动态权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                StrictMode.setVmPolicy(builder.build());
            }
            initView();
        }
    
    
        private Uri ImageUri;
        public static final int TAKE_PHOTO = 101;
        public static final int TAKE_CAMARA = 100;
    
        private void initView() {
            cameraBt = (Button) findViewById(R.id.camera_bt);
            photoBt = (Button) findViewById(R.id.photo_bt);
            camereIv = (ImageView) findViewById(R.id.camere_iv);
            photoIv = (ImageView) findViewById(R.id.photo_iv);
    
            cameraBt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //检查是否已经获得相机的权限
                    if (verifyPermissions(MainActivity.this, PERMISSIONS_STORAGE[2]) == 0) {
                        Log.i(TAG, "提示是否要授权");
                        ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS_STORAGE, 3);
                    } else {
                        //已经有权限
                        toCamera();  //打开相机
                    }
                }
            });
            photoBt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    toPicture();
                }
            });
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) {
                case TAKE_PHOTO:
                    if (resultCode == RESULT_OK) {
                        try {
                            //将拍摄的照片显示出来
                            Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(ImageUri));
                            camereIv.setImageBitmap(bitmap);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case TAKE_CAMARA:
                    if (resultCode == RESULT_OK) {
                        try {
                            //将相册的照片显示出来
                            Uri uri_photo = data.getData();
                            Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri_photo));
                            photoIv.setImageBitmap(bitmap);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    
    
        /**
         * 检查是否有对应权限
         *
         * @param activity   上下文
         * @param permission 要检查的权限
         * @return 结果标识
         */
        public int verifyPermissions(Activity activity, java.lang.String permission) {
            int Permission = ActivityCompat.checkSelfPermission(activity, permission);
            if (Permission == PackageManager.PERMISSION_GRANTED) {
                Log.i(TAG, "已经同意权限");
                return 1;
            } else {
                Log.i(TAG, "没有同意权限");
                return 0;
            }
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            if (grantResults != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.i(TAG, "用户授权");
                toCamera();
            } else {
                Log.i(TAG, "用户未授权");
            }
        }
    
        //跳转相册
        private void toPicture() {
            Intent intent = new Intent(Intent.ACTION_PICK);  //跳转到 ACTION_IMAGE_CAPTURE
            intent.setType("image/*");
            startActivityForResult(intent, TAKE_CAMARA);
            Log.i(TAG, "跳转相册成功");
        }
    
        //跳转相机
        private void toCamera() {
            //创建File对象,用于存储拍照后的图片
    //        File outputImage = new File(getExternalCacheDir(), "outputImage.jpg");
            File outputImage = new File(getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
            if (outputImage.exists()) {
                outputImage.delete();
            } else {
                try {
                    outputImage.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //判断SDK版本高低,ImageUri方法不同
            if (Build.VERSION.SDK_INT >= 24) {
                ImageUri = FileProvider.getUriForFile(MainActivity.this, "com.mooc.uploadfile4.fileprovider", outputImage);
            } else {
                ImageUri = Uri.fromFile(outputImage);
            }
    
            //启动相机程序
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, ImageUri);
            startActivityForResult(intent, TAKE_PHOTO);
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Android Studio 上传文件实例_拍照、相机上传图片

          本文链接:https://www.haomeiwen.com/subject/watsyktx.html