Android多媒体之调用摄像头和从本地相册中选择图片

概述:

这个例程的实现的功能是:拍照,自动压缩图片,以及从本地相册选择图片。
需要加载权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

demo:

public class MainActivity extends Activity implements View.OnClickListener {
    private Button mButtonTakePhoto;
    private Button mButtonGetPhoto;
    private ImageView mImageViewPhoto;

    private File mFile;//存储图片的文件

    public static final int GET_PIC_FROM_CAMERA = 0x123;
    public static final int GET_PIC_FROM_GALLERY = 0X124;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mButtonTakePhoto = (Button) findViewById(R.id.button_take_photo);
        mButtonGetPhoto = (Button) findViewById(R.id.button_get_photo);

        mImageViewPhoto = (ImageView) findViewById(R.id.imageView_camera);
//        mImageViewPhoto.setImageURI(Uri.fromFile(new File("/mnt/sdcard/1442309575248.jpg")));
        mButtonTakePhoto.setOnClickListener(this);
        mButtonGetPhoto.setOnClickListener(this);


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case GET_PIC_FROM_CAMERA:
                if (resultCode == RESULT_OK) {
                    ImageZip.zipImage(mFile.getAbsolutePath());//压缩图片
                    mImageViewPhoto.setImageURI(Uri.fromFile(mFile));
                }
                break;
            case GET_PIC_FROM_GALLERY:
                if(resultCode==RESULT_OK){
                    getImageFromGallery(data);
                }
                break;
        }
    }

    /**
     * 从本地相册中选择并得到相片
     */
    private void getImageFromGallery(Intent data) {
        Uri selectedImage = data.getData();
        //用一个String数组存储相册所有图片
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        //用一个Cursor对象的到相册的所有内容
        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();
        //得到选中图片下标
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        //得到所选的相片路径
        String picturePath = cursor.getString(columnIndex);
        //关闭Cursor,以免占用资源
        cursor.close();
        ImageZip.zipImage(picturePath);//一般相册中图片太大,不能直接显示,需要压缩图片
        //用一个ImageView展示该图片
        mImageViewPhoto.setImageBitmap(BitmapFactory.decodeFile(picturePath));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_take_photo:
                getPictureFromCamera();
                break;
            case R.id.button_get_photo:
                /*Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("");
                startActivityForResult(intent, GET_PIC_FROM_GALLERY);*/
                //左起参数:选择行为权限,系统本地相册URI路径
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                //向onActivityResult发送intent,requestCode为GET_PIC_FROM_GALLERY
                startActivityForResult(i, GET_PIC_FROM_GALLERY);
                break;
        }
    }
    /**
     * 向onActivityResult发出请求,的到拍摄生成的图片
     */
    private void getPictureFromCamera() {
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        //确定存储拍照得到的图片文件路径
        mFile = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
        try {
            mFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //加载Uri型的文件路径
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
        //向onActivityResult发送intent,requestCode为GET_PIC_FROM_CAMERA
        startActivityForResult(intent, GET_PIC_FROM_CAMERA);
    }
}

压缩图片的类:

public class ImageZip {
    /**
     * 压缩图片的方法
     */
    public static void zipImage(String savePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(savePath, options);
        options.inSampleSize = computeInitialSampleSize(options, 480, 480 * 960);
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(savePath, options);
        try {
            FileOutputStream fos = new FileOutputStream(savePath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        bitmap.recycle();
        bitmap = null;
        System.gc();
    }

    public static Bitmap getZipImage(String savePath){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(savePath, options);
        options.inSampleSize = computeInitialSampleSize(options, 480, 480 * 960);
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(savePath, options);
        bitmap.recycle();
        bitmap = null;
        System.gc();
        return bitmap;
    }

    public int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength,
                maxNumOfPixels);
        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }
        return roundedSize;
    }

    public static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;
        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
                .sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
                Math.floor(w / minSideLength), Math.floor(h / minSideLength));
        if (upperBound < lowerBound) {
            // return the larger one when there is no overlapping zone.
            return lowerBound;
        }
        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }
}

布局:

<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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button_take_photo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Take Photo"/>

        <Button
            android:id="@+id/button_get_photo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Get From Gallery"/>
    </LinearLayout>

    <ImageView
        android:id="@+id/imageView_camera"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

我们猿类工作压力大,很需要有自己的乐趣,于是乎,我开通了音乐人账号,以后的作品将会上传到我的音乐人小站上。如果这篇博客帮助到您,希望您能多关注,支持,鼓励我将创作进行下去,同时也祝你能在工作和生活乐趣两发面都能出彩!

网易云音乐人,直接打开客户端搜索音乐人 “星河河”

豆瓣音乐人地址:https://site.douban.com/chuxinghe/ 星河河

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值