项目地址 https://github.com/16ren/Androidgetphoto.git
MainActivity.java
package com.example.androidgetphoto;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
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.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private int REQUEST_CAMERA = 3621;
private int SELECT_FILE = 6523;
private Button bt_getphoto;
private ImageView iv_main_test;
private String mCurrentPhotoPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_getphoto = (Button) (findViewById(R.id.bt_getphoto));
iv_main_test = (ImageView) findViewById(R.id.iv_main_test);
bt_getphoto.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
getphoto();
}
});
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
setPic();
galleryAddPic();
} else if (requestCode == SELECT_FILE) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mCurrentPhotoPath = cursor.getString(columnIndex);
cursor.close();
setPic();
}
}
}
private void setPic() {
// Get the dimensions of the View
int targetW = iv_main_test.getWidth();
int targetH = iv_main_test.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
iv_main_test.setImageBitmap(bitmap);
}
private void getphoto() {
final String[] items = { "Gallery", "Camera", "Cancel" };
Builder builder = new Builder(this);
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Camera")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
try {
File f = createImageFile();
// if you set MediaStore.EXTRA_OUTPUT the intent
// maybe null in some div
// set the postion that image save
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, REQUEST_CAMERA);
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (items[item].equals("Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
// Add the Photo to a Gallery
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidgetphoto"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboard|keyboardHidden|screenSize" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<RelativeLayout 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"
tools:context="com.example.androidgetphoto.MainActivity" >
<Button
android:id="@+id/bt_getphoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:text="@string/getphoto" />
<ImageView
android:id="@+id/iv_main_test"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerInParent="true"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Androidgetphoto</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
<string name="getphoto">get photo</string>
</resources>
使用中的问题和解决方案
1.权限.
保存拍照的图片到本地
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
使用
拍照功能
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
2.拍照图片返回形式
(1)直接返回
不指定图片保存位置 ,直接Bitmap bp =(Bitmap) data.getData()。这种形式获取到的只是一个拍照的缩略图,对于一搬的头像够用。
(2)先保存再读取
使用 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));指定拍照后图片保存的位置,这时要在activity中维护一个路径全局变量(private String mCurrentPhotoPath;);
这种情况可以获取一个没有压缩的图片,这种方式有些机型适配的问题,有些手机拍照成功,有些手机拍完照后确定返回后mCurrentPhotoPath数据为空,被销毁了。
解决方案 在AndroidManifest.xml加上 android:configChanges="orientation|keyboard|keyboardHidden|screenSize" MainActivity.java 重载onConfigurationChanged(Configuration newConfig)
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboard|keyboardHidden|screenSize" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
@Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO什么也不做
super.onConfigurationChanged(newConfig);}
(3)讲拍照后的图片添加到画廊,当然不添加也可以,只不过你手机自带的相册就里面不会显示你刚才拍摄的图片
// Add the Photo to a Gallery
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
(4)内存不足的问题
对于一些手机拍照获取高清的图片,直接进行加载显示有时会内存不足,从而程序崩溃。
解决方式可以参照 http://blog.csdn.net/yudajun/article/details/9323941