获取拍照图片
点击按钮,onClick()中 调用 takePhoto()
Uri imageFileUri = null;
protected void takePhoto() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss",
Locale.CHINA);
String imageFilePath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/" + sdf.format(new Date()) + ".png";// 设置图片的保存路径
File imageFile = new File(imageFilePath);// 通过路径创建保存文件
imageFileUri = Uri.fromFile(imageFile);// 获取文件的Uri
Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 跳转到相机Activity
it.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);// 告诉相机拍摄完毕输出图片到指定的Uri
startActivityForResult(it, REQUEST_CODE_TAKE_PHOTO);
}
imageFileUri 是全局变量。
private void showTakenPhoto() {
ImageView iv = (ImageView) findViewById(R.id.iv_image);
if(imageFileUri != null && !TextUtils.isEmpty(imageFileUri.getPath())) {
iv.setImageURI(imageFileUri);
}
}
获取图库图片
发送请求:
private void pickPhoto() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, REQUEST_CODE_PICK_PHOTO);
}
显示图片:
此处做一下说明,在onActivityResult() 中可以获取图片对应的uri,然后直接用ImageView显示出来。这种情况可行,但是很容易出现OutOfMemoryError。
ERROR CODE:
/**
* OutOfMemoryError
*
* @param photoUri
*/
private void showPhoto1(Uri photoUri) {
ImageView ivv = (ImageView) findViewById(R.id.iv_image);
ContentResolver cr = this.getContentResolver();
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(cr.openInputStream(photoUri));
ivv.setImageBitmap(bitmap);
/* Can not draw recycled bitmaps
if(!bitmap.isRecycled()) {
bitmap.recycle();
bitmap = null;
} */
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* OutOfMemoryError
*
* @param photoUri
*/
private void showPhoto2(Uri photoUri) {
ImageView ivv = (ImageView) findViewById(R.id.iv_image);
ivv.setImageURI(photoUri);
}
参考了官方文档解决方法: http://developer.android.com/training/displaying-bitmaps/index.html
总的思想就是压缩图片,官网中用的方法是 BitmapFacotry.decodeResource(),我这里把它改成了BitmapFacotry.decodeFile()。也用过BitmapFactory.decodeStream(),不过用的不是很爽,decode的bitmap为null,提示 SkImageDecoder::Factory returned null。 如 http://522656914.iteye.com/blog/1876181
CODE:
private void showGalleryPhoto(Intent data) {
if (data == null) {
return;
}
Uri photoUri = data.getData();
if (photoUri == null) {
return;
}
String[] pojo = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(photoUri, pojo, null, null, null);
String picPath = null;
if (cursor != null) {
int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
cursor.moveToFirst();
picPath = cursor.getString(columnIndex);
// cursor.close(); android.database.StaleDataException: Attempted to access a cursor after it has been closed.
}
if(!TextUtils.isEmpty(picPath)) {
Bitmap bitmap = decodeBitmapFromFilePath(picPath, 600, 600);
ImageView ivv = (ImageView) findViewById(R.id.iv_image);
ivv.setImageBitmap(bitmap);
}
}
/**
* 通过图片路径调用BitmapFactory.decodeFile() 压缩图片
*
* @param picPath
* @param reqWidth
* @param reqHeight
* @return
*/
public static Bitmap decodeBitmapFromFilePath(String picPath, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picPath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(picPath, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
onActivityResult() 调用 showGalleryPhoto()即可,calculateInSampleSize() 照搬官网,decodeBitmapFromFilePath()也是官网的代码,自己做了修改。
共享View的截图,即View的screenshot
public void shareViewScreenshot() {
RelativeLayout rlytMain = (RelativeLayout) findViewById(R.id.rlyt_main);
Intent intent = getShareIntentOf(rlytMain, "我的共享视图。。。");
if (intent != null) {
startActivity(Intent.createChooser(intent, "title..."));
}
}
/**
* 获取share的intent, 需要权限 "android.permission.WRITE_EXTERNAL_STORAGE"
* @param view
* @param text
* @return
*/
protected Intent getShareIntentOf(View view, String text) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_SUBJECT, "Share");
intent.putExtra(Intent.EXTRA_TEXT, text);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss",
Locale.CHINA);
String fname = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/" + sdf.format(new Date()) + ".png";
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
if (bitmap != null) {
try {
FileOutputStream out = new FileOutputStream(fname);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
File f = new File(fname);
if (f != null && f.exists() && f.isFile()) {
Uri u = Uri.fromFile(f);
intent.putExtra(Intent.EXTRA_STREAM, u);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
} else {
return null;
}
return intent;
}
记得加权限: "android.permission.WRITE_EXTERNAL_STORAGE"
shareViewScreenshot()方法中的 RelativeLayout rlytMain 就是要共享的图片。
以下图片是共享到微信后在微信浏览的结果:
与前一张相比, 这张图片的背景比较黑,因为这个是 RelativeLayout rlytMain 的背景。