最近在做一个使用名片全能王扫描名片的项目,需要使用相机进行拍照或者从相册中选取照片,下面主要是调用相机拍照和从相册中选取照片的方法。
调用相机拍照或者从相册中选取照片,完整的类如下:
package com.cool.takeandpickphoto;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int PHOTO_WITH_CAMERA = 0;
private static final int PHOTO_WITH_DATA = 1;
private String imgName = "";
private ImageView iv_photo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv_photo = (ImageView) findViewById(R.id.iv_photo);
}
/**
* 拍照
*
* @param v
*/
public void takePhoto(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // 调用系统相机
Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "image.jpg"));
// 指定照片保存路径(SD卡),image.jpg为一个临时文件,每次拍照后这个图片都会被替换
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
// 直接使用,没有缩小
startActivityForResult(intent, PHOTO_WITH_CAMERA); // 用户点击了从相机获取
}
/**
* 从相册中选取照片
*
* @param v
*/
public void pickPhoto(View v) {
Intent intent = new Intent();
intent.setType("image/*"); // 开启Pictures画面Type设定为image
intent.setAction(Intent.ACTION_GET_CONTENT); // 使用Intent.ACTION_GET_CONTENT这个Action
startActivityForResult(intent, PHOTO_WITH_DATA); // 取得相片后返回到本画面
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) { // 返回成功
switch (requestCode) {
case PHOTO_WITH_CAMERA: {// 拍照获取图片
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED)) { // 是否有SD卡
Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/image.jpg");
imgName = createPhotoFileName();
// 保存图片
savePhotoToSDCard("/sdcard/photos", imgName, bitmap);
if (bitmap != null) {
// 为防止原始图片过大导致内存溢出,这里先缩小原图显示,然后释放原始Bitmap占用的内存
Bitmap smallBitmap = zoomBitmap(bitmap, bitmap.getWidth() / 5,
bitmap.getHeight() / 5);
iv_photo.setImageBitmap(smallBitmap);
}
Toast.makeText(this, "照片已经保存", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "没有SD卡", Toast.LENGTH_LONG).show();
}
break;
}
case PHOTO_WITH_DATA: {// 从图库中选择图片
ContentResolver resolver = getContentResolver();
// 照片的原始资源地址
Uri originalUri = data.getData();
// Log.e("399",originalUri.toString());
// content://media/external/images/media/15838 "
try {
// 使用ContentProvider通过URI获取原始图片
Bitmap photo = MediaStore.Images.Media.getBitmap(resolver, originalUri);
imgName = createPhotoFileName();
savePhotoToSDCard("/sdcard/photos", imgName, photo);
if (photo != null) {
// 为防止原始图片过大导致内存溢出,这里先缩小原图显示,然后释放原始Bitmap占用的内存
Bitmap smallBitmap = zoomBitmap(photo, photo.getWidth() / 5,
photo.getHeight() / 5);
iv_photo.setImageBitmap(smallBitmap);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
/** 创建图片不同的文件名 **/
private String createPhotoFileName() {
String fileName = "";
Date date = new Date(System.currentTimeMillis()); // 系统当前时间
SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
fileName = dateFormat.format(date) + ".jpg";
return fileName;
}
/**
* 保存照片到SDCard
*
* @param path
* 需要保存的路径
* @param photoName
* 保存的相片名字
* @param photoBitmap
* 照片的Bitmap对象
*/
private void savePhotoToSDCard(String path, String photoName, Bitmap photoBitmap) {
FileOutputStream fileOutputStream = null;
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
File photoFile = new File(path, photoName);
try {
fileOutputStream = new FileOutputStream(photoFile);
if (photoBitmap != null) {
if (photoBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)) {
fileOutputStream.flush();
fileOutputStream.close();
}
}
} catch (FileNotFoundException e) {
photoFile.delete();
e.printStackTrace();
} catch (IOException e) {
photoFile.delete();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
private Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidth = ((float) width / w);
float scaleHeight = ((float) height / h);
matrix.postScale(scaleWidth, scaleHeight);
Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
return newbmp;
}
}
布局文件:
<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"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="拍照获取照片"
android:textSize="18sp"
android:onClick="takePhoto" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="从相册中选取照片"
android:textSize="18sp"
android:onClick="pickPhoto" />
<ImageView
android:id="@+id/iv_photo"
android:layout_width="200dp"
android:layout_height="300dp"
/>
</LinearLayout>