android讀取相冊照片和相機照片

  之前在讀取照片的時候總是遇到一個問題,就是在照相機裏讀出的照片像素高,沒辦法放到自己定義好的imageview中,但是如果用bundle的方法讀取的話,獨處的像素很低,圖片根本看不清,所以我決定採用把相機裏的圖片先存到手機的文檔中,然後在文檔中通過壓縮的方式讀取照片就ok了。壓縮圖片需要BitmapFactory.options

 

final BitmapFactory.Options options=new BitmapFactory.Options();
			options.inJustDecodeBounds=true;
			BitmapFactory.decodeFile(mUri.getPath(), options);
			options.inSampleSize=calculateInSampleSize(options, 275, 275);
			options.inJustDecodeBounds=false;
			Bitmap bitmap=BitmapFactory.decodeFile(mUri.getPath(), options);
			imageview.setImageBitmap(bitmap);

calculateInSampleSize是進行圖片裁剪的函數。下面將會給出。

options.inJustDecodeBounds大家可以查一下它的含義就會明白怎樣設true和false

public static int calculateInSampleSize(BitmapFactory.Options options,
			int resWidth,int resHeigth){
		//原始照片的高和寬
		final int heigth=options.outHeight;
		final int width=options.outWidth;
	    int inSampleSize=1;
		// 計算壓縮的比例:分爲寬高比例
	    final int heigthRatio=Math.round((float)heigth/(float)resHeigth);
	    final int widthRadtio=Math.round((float)width/(float)resWidth);
	    inSampleSize=heigthRatio<widthRadtio?heigthRatio:widthRadtio;
	    return inSampleSize;
	}

ok下面我將給出全部的代碼。記得要添加相機權限在清單裏。

package com.example.facedatect1;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Map;

import android.R.id;
import android.R.integer;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
	private Button picbtn;
	private Button cambtn;
	private ImageView imageview;
	public static final int TAKE_PIC=1;
	public static final int TAKE_CAM=2;
	private Uri mUri=null;//圖片路徑
	private String filename;//圖片名稱
	private Bitmap bit;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		imageview=(ImageView)findViewById(R.id.imageView1);
		picbtn=(Button)findViewById(R.id.picbtn);
		picbtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent();
				intent.setType("image/*");
				//使用Intent.ACTION_GET_CONTENT
				intent.setAction(Intent.ACTION_GET_CONTENT);
				/* 取得相片後返回本畫面 */ 
				startActivityForResult(intent, TAKE_PIC);
			}
		});
		cambtn=(Button)findViewById(R.id.camarabtn);
		cambtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 先建立一個保存圖片的文件,再進行拍照事件的觸發
				SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmSS");
				Date date=new Date(System.currentTimeMillis());
				filename=format.format(date);
				//創建File對象用於存儲拍照的圖片 SD卡根目錄           
	            //存儲至DCIM文件夾
				File path=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
				File outputImage=new File(path,filename+".jpg");
				try {
	                if(outputImage.exists()) {
	                    outputImage.delete();
	                }
	                outputImage.createNewFile();
	            } catch(IOException e) {
	                e.printStackTrace();
	            }
				//將File對象轉換爲Uri並啓動照相程序
				mUri=Uri.fromFile(outputImage);
				Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);//指定圖片輸出地址
				startActivityForResult(intent, TAKE_CAM);
			}
		});
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK) { 
            Toast.makeText(MainActivity.this, "照相失敗"+resultCode, Toast.LENGTH_SHORT).show();
            return; 
        }
		switch (requestCode) {
		case TAKE_PIC:
		    mUri=data.getData();
			Log.e("uri", "-------->>"+mUri);
			ContentResolver cr=this.getContentResolver();
			final BitmapFactory.Options option=new BitmapFactory.Options();
			option.inJustDecodeBounds=true;
			try {
				BitmapFactory.decodeStream(cr.openInputStream(mUri), null, option);
			} catch (FileNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			option.inSampleSize=calculateInSampleSize(option, 275, 275);
                    //275是自己設的截圖後的大小,大家可以根據自己的需求自己定義
			option.inJustDecodeBounds=false;
			
			try {
				bit = BitmapFactory.decodeStream(cr.openInputStream(mUri), null, option);
				imageview.setImageBitmap(bit);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case TAKE_CAM:
			final BitmapFactory.Options options=new BitmapFactory.Options();
			options.inJustDecodeBounds=true;
			BitmapFactory.decodeFile(mUri.getPath(), options);
			options.inSampleSize=calculateInSampleSize(options, 275, 275);
			options.inJustDecodeBounds=false;
			bit=BitmapFactory.decodeFile(mUri.getPath(), options);
			imageview.setImageBitmap(bit);
			break;
		}
	}
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int resWidth,int resHeigth){
		//原始照片的高和寬
		final int heigth=options.outHeight;
		final int width=options.outWidth;
	    int inSampleSize=1;
		// 計算壓縮的比例:分爲寬高比例
	    if (heigth > resHeigth || width > resWidth) {
	    final int heigthRatio=Math.round((float)heigth/(float)resHeigth);
	    final int widthRadtio=Math.round((float)width/(float)resWidth);
	    inSampleSize=heigthRatio<widthRadtio?heigthRatio:widthRadtio;}
	    return inSampleSize;
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章