Android实现拍照,相册选取、剪切图片功能

1.代码如下

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;

import butterknife.BindView;
import butterknife.ButterKnife;


public class MainActivity extends AppCompatActivity {

    private static final int TAKE_PHOTO = 1000;
    private static final int CHOOSE_PHOTO = 2000;
    private static final int CROP_PHOTO = 3000;
    private String imagePath;
    private Uri imageUri;

    @BindView(R.id.take_photo_button)
    Button take_photo_button;
    @BindView(R.id.choose_from_album_button)
    Button choose_from_album_button;
    @BindView(R.id.picture_imageView )
    ImageView picture_imageView ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        imagePath = getExternalCacheDir() + "/image.jpg"; // 设置文件保存的路径
        initView();
    }


    private void initView() {
        take_photo_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageUri = file2Uri(imagePath);
                takePhoto(imageUri);
            }
        });


        choose_from_album_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openAlbum();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case TAKE_PHOTO:
                // 裁剪拍摄的照片
                imageUri = cropPhoto(imageUri);
                break;

            case CHOOSE_PHOTO:
                // 裁剪从相册选择的照片
                Uri uri = data.getData();
                imageUri = cropPhoto(uri);
                break;

            case CROP_PHOTO:
                // 显示图片
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = false; // false表示返回Bitmap;true表示返回null,获取图片信息的时候用
                options.inSampleSize = 2; // 设置图片宽高为原图的1/2
                Bitmap bitmap = null;
                try {
                    InputStream ins = getContentResolver().openInputStream(imageUri);
                    bitmap = BitmapFactory.decodeStream(ins, null, options);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                /*Cursor cursor = getContentResolver().query(imageUri, null, null, null, null);
                if (null != cursor) {
                    if (cursor.moveToFirst()) {
                        imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    }
                }*/
                // bitmap = BitmapFactory.decodeFile(imagePath, options);
                picture_imageView.setImageBitmap(bitmap);
                break;

            default:
                break;
        }
    }


    /**
     * 创建图片的File对象并转化成Uri返回
     * @return
     */
    private Uri file2Uri(String imagePath) {
        Uri uri = null;
        File file = new File(imagePath);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(MainActivity.this, "cn.com.pirate.demo.fileprovier", file);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }


    /**
     * 启动相机
     * @param uri
     */
    private void takePhoto(Uri uri) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, TAKE_PHOTO);
    }


    /**
     * 打开相册
     */
    private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        // Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);
    }


    /**
     * 裁切图片并返回Uri
     * @param uri
     */
    private Uri cropPhoto(Uri uri) {
        Uri imageUri = Uri.fromFile(new File(imagePath));
        Intent intent = new Intent("com.android.camera.action.CROP");
        // 赋予权限,否则7.0以上版本无法裁切图片
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);
        // aspectX,aspectY是宽高的比例  
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX,outputY是裁剪图片宽高  
        // intent.putExtra("outputX", 800);
        // intent.putExtra("outputY", 800);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, CROP_PHOTO);
        return imageUri;
    }
}

2.在AndroidManifest.xml中添加

<provider
    android:authorities="cn.com.pirate.demo.fileprovier"
    android:name="android.support.v4.content.FileProvider"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_path"/>
</provider>

3.在res文件加下添加xml/file_path.xml文件,内容如下

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name = "share" path = "" />
</paths>

4.对应的布局文件为layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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"
    android:orientation="vertical"
    tools:context="cn.com.pirate.demo.MainActivity">

    <Button
        android:id="@+id/take_photo_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="5dp"
        android:textAllCaps="false"
        android:text="take_photo"/>

    <Button
        android:id="@+id/choose_from_album_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:textAllCaps="false"
        android:text="choose_from_album"/>

    <ImageView
        android:id="@+id/picture_imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal"/>

</LinearLayout>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,470评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,393评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,577评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,176评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,189评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,155评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,041评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,903评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,319评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,539评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,703评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,417评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,013评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,664评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,818评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,711评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,601评论 2 353

推荐阅读更多精彩内容