1.activity
package com.example.camera;
import java.io.File;
import android.app.Activity;
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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private Button btnPhoto;
private ImageView imageView;
private Uri uri;
private final int TAKE_PICTURE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView1);
btnPhoto = (Button) findViewById(R.id.button1);
btnPhoto.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
File file = new File(Environment.getExternalStorageDirectory(), "test.jpg");
uri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, TAKE_PICTURE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PICTURE) {
if (data != null) {
if (data.hasExtra("data")) {
Bitmap bitmap = data.getParcelableExtra("data");
imageView.setImageBitmap(bitmap);
}
} else {
int width = imageView.getWidth();
int height = imageView.getHeight();
BitmapFactory.Options options = new BitmapFactory.Options();
// If set to true, the decoder will return null (no bitmap), but
// the out…
// 也就是说,如果我们把它设为true,那么BitmapFactory.decodeFile(String path,
// Options opt)并不会真的返回一个Bitmap给你,
// 它仅仅会把它的宽,高取回来给你,这样就不会占用太多的内存,也就不会那么频繁的发生OOM了。
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(uri.getPath(), options);
int imageWidth = options.outWidth;
int imageHeight = options.outHeight;
int scale = Math.min(imageWidth / width, imageHeight / height);
options.inJustDecodeBounds = false;
// 节约内存
options.inSampleSize = scale;
options.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(uri.getPath(), options);
imageView.setImageBitmap(bitmap);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
2.布局文件
<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:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/ic_launcher" />
</LinearLayout>
3.效果图
4.源码地址:点击下载代码