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

Android拍照Camera(二)

2016-02-17 14:07 375 查看
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android_custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="btn" >
</Button>

<ImageView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/btn"
android:scaleType="center" >
</ImageView>

</RelativeLayout>


public class MainActivity extends Activity implements OnClickListener {
private static final int REQUEST_CODE_IMAGE_CATURE = 0x11;
private static final int REQUEST_CODE_IMAGE_CATURE_CROP = 0x12;

ImageView img;
Uri imgUri;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.paomadeng);
img = (ImageView) findViewById(R.id.img);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(this);
}

@Override
public void onClick(View v) {
if (v.getId() == R.id.btn) {
takePicture();
}
}

/**
* 拍摄照片并保存
*/
public void takePicture() {
String imgPath = Environment.getExternalStorageDirectory() + File.separator + "tmp.png";
File file = new File(imgPath);
if (file.exists()) {
file.delete();
}

try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imgUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
startActivityForResult(intent, REQUEST_CODE_IMAGE_CATURE);
}

/**
* 裁剪图片
*/
public void cropPicture() {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(imgUri, "image/*");
intent.putExtra("scale", true);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
startActivityForResult(intent, REQUEST_CODE_IMAGE_CATURE_CROP);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode != Activity.RESULT_OK) {
return;
}

if (requestCode == REQUEST_CODE_IMAGE_CATURE) {
cropPicture();
} else if (requestCode == REQUEST_CODE_IMAGE_CATURE_CROP) {
InputStream is = null;
try { // 根据文件Uri,读取输入流
is = getContentResolver().openInputStream(imgUri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
img.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: