您的位置:首页 > 移动开发 > Android开发

android读取相册照片和相机照片

2015-12-14 10:53 585 查看
之前在读取照片的时候总是遇到一个问题,就是在照相机里读出的照片像素高,没办法放到自己定义好的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);
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: