Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android多媒體之調用攝像頭和從本地相冊中選擇圖片

Android多媒體之調用攝像頭和從本地相冊中選擇圖片

編輯:關於Android編程

概述:

這個例程的實現的功能是:拍照,自動壓縮圖片,以及從本地相冊選擇圖片。
需要加載權限:

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;
        }
    }
}

布局:



    

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved