轉載請注明出處:http://blog.csdn.net/loveyaozu/article/details/51160482
相信有非常多Android開發者在日常開發中,因為項目需求,須要我們的APP可以從相冊中選取圖片並剪輯。以及拍照剪輯后上傳的功能。
假設之前你沒有做過這個功能,剛開始做的時候可能會遇到一些列的問題,這些問題大多是細節上的問題。今天,就依據自己的開發經驗,給大家提供一套完畢的相冊圖片選取剪輯和拍照剪輯的代碼事例。我提供的代碼可能還會存在一些問題,大家可以相互交流學習。
這里會給大家提供一些我整理的一些圖片處理的工具類,供大家使用。
拍照,相冊圖片選取以及圖片剪輯的工具類。PhotoUtils.java
package com.syz.photograph;
import java.io.File;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
public class PhotoUtil {
public static final int NONE = 0;
public static final String IMAGE_UNSPECIFIED = "image/*";//隨意圖片類型
public static final int PHOTOGRAPH = 1;// 拍照
public static final int PHOTOZOOM = 2; // 縮放
public static final int PHOTORESOULT = 3;// 結果
public static final int PICTURE_HEIGHT = 500;
public static final int PICTURE_WIDTH = 500;
public static String imageName;
/**
* 從系統相冊中選取照片上傳
* @param activity
*/
public static void selectPictureFromAlbum(Activity activity){
// 調用系統的相冊
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
IMAGE_UNSPECIFIED);
// 調用剪切功能
activity.startActivityForResult(intent, PHOTOZOOM);
}
/**
* 從系統相冊中選取照片上傳
* @param fragment
*/
public static void selectPictureFromAlbum(Fragment fragment){
// 調用系統的相冊
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
IMAGE_UNSPECIFIED);
// 調用剪切功能
fragment.startActivityForResult(intent, PHOTOZOOM);
}
/**
* 拍照
* @param activity
*/
public static void photograph(Activity activity){
imageName = File.separator + getStringToday() + ".jpg";
// 調用系統的拍照功能
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String status = Environment.getExternalStorageState();
if(status.equals(Environment.MEDIA_MOUNTED)){
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
Environment.getExternalStorageDirectory(), imageName)));
}else{
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
activity.getFilesDir(), imageName)));
}
activity.startActivityForResult(intent, PHOTOGRAPH);
}
/**
* 拍照
* @param fragment
*/
public static void photograph(Fragment fragment){
imageName = "/" + getStringToday() + ".jpg";
// 調用系統的拍照功能
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String status = Environment.getExternalStorageState();
if(status.equals(Environment.MEDIA_MOUNTED)){
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
Environment.getExternalStorageDirectory(), imageName)));
}else{
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
fragment.getActivity().getFilesDir(), imageName)));
}
fragment.startActivityForResult(intent, PHOTOGRAPH);
}
/**
* 圖片裁剪
* @param activity
* @param uri
* @param height
* @param width
*/
public static void startPhotoZoom(Activity activity,Uri uri,int height,int width) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
intent.putExtra("crop", "true");
// aspectX aspectY 是寬高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪圖片寬高
intent.putExtra("outputX", height);
intent.putExtra("outputY", width);
intent.putExtra("noFaceDetection", true); //關閉人臉檢測
intent.putExtra("return-data", true);//假設設為true則返回bitmap
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//輸出文件
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
activity.startActivityForResult(intent, PHOTORESOULT);
}
/**
* 圖片裁剪
* @param activity
* @param uri 原圖的地址
* @param height 指定的剪輯圖片的高
* @param width 指定的剪輯圖片的寬
* @param destUri 剪輯后的圖片存放地址
*/
public static void startPhotoZoom(Activity activity,Uri uri,int height,int width,Uri destUri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
intent.putExtra("crop", "true");
// aspectX aspectY 是寬高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪圖片寬高
intent.putExtra("outputX", height);
intent.putExtra("outputY", width);
intent.putExtra("noFaceDetection", true); //關閉人臉檢測
intent.putExtra("return-data", false);//假設設為true則返回bitmap
intent.putExtra(MediaStore.EXTRA_OUTPUT, destUri);//輸出文件
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
activity.startActivityForResult(intent, PHOTORESOULT);
}
/**
* 圖片裁剪
* @param fragment
* @param uri
* @param height
* @param width
*/
public static void startPhotoZoom(Fragment fragment,Uri uri,int height,int width) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
intent.putExtra("crop", "true");
// aspectX aspectY 是寬高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪圖片寬高
intent.putExtra("outputX", height);
intent.putExtra("outputY", width);
intent.putExtra("return-data", true);
fragment.startActivityForResult(intent, PHOTORESOULT);
}
/**
* 獲取當前系統時間並格式化
* @return
*/
@SuppressLint("SimpleDateFormat")
public static String getStringToday() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 制作圖片的路徑地址
* @param context
* @return
*/
public static String getPath(Context context){
String path = null;
File file = null;
long tag = System.currentTimeMillis();
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
//SDCard是否可用
path = Environment.getExternalStorageDirectory() + File.separator +"myimages/";
file = new File(path);
if(!file.exists()){
file.mkdirs();
}
path = Environment.getExternalStorageDirectory() + File.separator +"myimages/"+ tag + ".png";
}else{
path = context.getFilesDir() + File.separator +"myimages/";
file = new File(path);
if(!file.exists()){
file.mkdirs();
}
path = context.getFilesDir() + File.separator +"myimages/"+ tag + ".png";
}
return path;
}
/**
* 按比例獲取bitmap
* @param path
* @param w
* @param h
* @return
*/
public static Bitmap convertToBitmap(String path, int w, int h) {
BitmapFactory.Options opts = new BitmapFactory.Options();
// 設置為ture僅僅獲取圖片大小
opts.inJustDecodeBounds = true;
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
BitmapFactory.decodeFile(path, opts);
int width = opts.outWidth;
int height = opts.outHeight;
float scaleWidth = 0.f, scaleHeight = 0.f;
if (width > w || height > h) {
// 縮放
scaleWidth = ((float) width) / w;
scaleHeight = ((float) height) / h;
}
opts.inJustDecodeBounds = false;
float scale = Math.max(scaleWidth, scaleHeight);
opts.inSampleSize = (int)scale;
WeakReference<Bitmap> weak = new WeakReference<Bitmap>(BitmapFactory.decodeFile(path, opts));
return Bitmap.createScaledBitmap(weak.get(), w, h, true);
}
/**
* 獲取原圖bitmap
* @param path
* @return
*/
public static Bitmap convertToBitmap2(String path) {
BitmapFactory.Options opts = new BitmapFactory.Options();
// 設置為ture僅僅獲取圖片大小
opts.inJustDecodeBounds = true;
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
// 返回為空
BitmapFactory.decodeFile(path, opts);
return BitmapFactory.decodeFile(path, opts);
}
}
圖片壓縮等一些列圖片處理的工具類 ImageUtils.java
package com.syz.photograph;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
/**
* 圖片處理的工具類
* @author yaozu
*
*/
public class ImageUtils {
private static final String TAG = ImageUtils.class.getSimpleName();
/**
* 依據Uri獲取路徑
* @param contentUri
* @return
*/
public static String getRealPathByURI(Uri contentUri,Context context) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri,
proj, null, null, null);
if (cursor.moveToFirst()) {
;
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
/**
* 創建一條圖片地址uri,用於保存拍照后的照片
*
* @param context
* @return 圖片的uri
*/
public static Uri createImagePathUri(Context context) {
Uri imageFilePath = null;
String status = Environment.getExternalStorageState();
SimpleDateFormat timeFormatter = new SimpleDateFormat(
"yyyyMMdd_HHmmss", Locale.CHINA);
long time = System.currentTimeMillis();
String imageName = timeFormatter.format(new Date(time));
// ContentValues是我們希望這條記錄被創建時包括的數據信息
ContentValues values = new ContentValues(3);
values.put(MediaStore.Images.Media.DISPLAY_NAME, imageName);
values.put(MediaStore.Images.Media.DATE_TAKEN, time);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
if (status.equals(Environment.MEDIA_MOUNTED)) {// 推斷是否有SD卡,優先使用SD卡存儲,當沒有SD卡時使用手機存儲
imageFilePath = context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
imageFilePath = context.getContentResolver().insert(
MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
}
Log.i("", "生成的照片輸出路徑:" + imageFilePath.toString());
return imageFilePath;
}
/**
* 圖片壓縮
*
* @param bmp
* @param file
*/
public static void compressBmpToFile(File file,int height,int width) {
Bitmap bmp = decodeSampledBitmapFromFile(file.getPath(), height, width);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int options = 100;
bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
/*while (baos.toByteArray().length / 1024 > 30) {
baos.reset();
if (options - 10 > 0) {
options = options - 10;
bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
if (options - 10 <= 0) {
break;
}
}*/
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 將圖片變成bitmap
*
* @param path
* @return
*/
public static Bitmap getImageBitmap(String path) {
Bitmap bitmap = null;
File file = new File(path);
if (file.exists()) {
bitmap = BitmapFactory.decodeFile(path);
return bitmap;
}
return null;
}
//=================================圖片壓縮方法===============================================
/**
* 質量壓縮
* @author ping 2015-1-5 下午1:29:58
* @param image
* @param maxkb
* @return
*/
public static Bitmap compressBitmap(Bitmap image,int maxkb) {
//L.showlog(壓縮圖片);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 質量壓縮方法,這里100表示不壓縮。把壓縮后的數據存放到baos中
image.compress(Bitmap.CompressFormat.JPEG, 50, baos);
int options = 100;
// 循環推斷假設壓縮后圖片是否大於(maxkb)50kb,大於繼續壓縮
while (baos.toByteArray().length / 1024 > maxkb) {
// 重置baos即清空baos
baos.reset();
if(options-10>0){
// 每次都降低10
options -= 10;
}
// 這里壓縮options%。把壓縮后的數據存放到baos中
image.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
// 把壓縮后的數據baos存放到ByteArrayInputStream中
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
// 把ByteArrayInputStream數據生成圖片
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
return bitmap;
}
/**
*
* @param res
* @param resId
* @param reqWidth
* 所需圖片壓縮尺寸最小寬度
* @param reqHeight
* 所需圖片壓縮尺寸最小高度
* @return
*/
public static Bitmap decodeSampledBitmapFromResource(Resources res,
int resId, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
/**
*
* @param filepath
* 圖片路徑
* @param reqWidth
* 所需圖片壓縮尺寸最小寬度
* @param reqHeight
* 所需圖片壓縮尺寸最小高度
* @return
*/
public static Bitmap decodeSampledBitmapFromFile(String filepath,int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filepath, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filepath, options);
}
/**
*
* @param bitmap
* @param reqWidth
* 所需圖片壓縮尺寸最小寬度
* @param reqHeight
* 所需圖片壓縮尺寸最小高度
* @return
*/
public static Bitmap decodeSampledBitmapFromBitmap(Bitmap bitmap,
int reqWidth, int reqHeight) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, baos);
byte[] data = baos.toByteArray();
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, 0, data.length, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeByteArray(data, 0, data.length, options);
}
/**
* 計算壓縮比例值(改進版 by touch_ping)
*
* 原版2>4>8...倍壓縮
* 當前2>3>4...倍壓縮
*
* @param options
* 解析圖片的配置信息
* @param reqWidth
* 所需圖片壓縮尺寸最小寬度O
* @param reqHeight
* 所需圖片壓縮尺寸最小高度
* @return
*/
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int picheight = options.outHeight;
final int picwidth = options.outWidth;
int targetheight = picheight;
int targetwidth = picwidth;
int inSampleSize = 1;
if (targetheight > reqHeight || targetwidth > reqWidth) {
while (targetheight >= reqHeight
&& targetwidth>= reqWidth) {
inSampleSize += 1;
targetheight = picheight/inSampleSize;
targetwidth = picwidth/inSampleSize;
}
}
Log.i("===","終於壓縮比例:" +inSampleSize + "倍");
Log.i("===", "新尺寸:" + targetwidth + "*" +targetheight);
return inSampleSize;
}
// 讀取圖像的旋轉度
public static int readBitmapDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
/**
* 將圖片依照某個角度進行旋轉
*
* @param bm
* 須要旋轉的圖片
* @param degree
* 旋轉角度
* @return 旋轉后的圖片
*/
public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
Bitmap returnBm = null;
// 依據旋轉角度,生成旋轉矩陣
Matrix matrix = new Matrix();
matrix.postRotate(degree);
try {
// 將原始圖片依照旋轉矩陣進行旋轉,並得到新的圖片
returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
} catch (OutOfMemoryError e) {
}
if (returnBm == null) {
returnBm = bm;
}
if (bm != returnBm) {
bm.recycle();
}
return returnBm;
}
/**
*
* @param mBitmap
* @param fileName
*/
public static void saveBitmapToLocal(Bitmap mBitmap,String fileName) {
if(mBitmap != null){
FileOutputStream fos = null;
try {
File file = new File(fileName);
if(file.exists()){
file.delete();
}
file.createNewFile();
fos = new FileOutputStream(file);
mBitmap.compress(Bitmap.CompressFormat.PNG, 80, fos);
fos.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(fos != null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 將下載下來的圖片保存到SD卡或者本地.並返回圖片的路徑(包括文件命和擴展名)
* @param context
* @param bitName
* @param mBitmap
* @return
*/
public static String saveBitmap(Context context,String bitName, Bitmap mBitmap) {
String path = null;
File f;
if(mBitmap != null){
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
f = new File(Environment.getExternalStorageDirectory() + File.separator +"images/");
String fileName = Environment.getExternalStorageDirectory() + File.separator +"images/"+ bitName + ".png";
path = fileName;
FileOutputStream fos = null;
try {
if(!f.exists()){
f.mkdirs();
}
File file = new File(fileName);
file.createNewFile();
fos = new FileOutputStream(file);
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(fos != null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
//本地存儲路徑
f = new File(context.getFilesDir() + File.separator +"images/");
Log.i(TAG, "本地存儲路徑:"+context.getFilesDir() + File.separator +"images/"+ bitName + ".png");
path = context.getFilesDir() + File.separator +"images/"+ bitName + ".png";
FileOutputStream fos = null;
try {
if(!f.exists()){
f.mkdirs();
}
File file = new File(path);
file.createNewFile();
fos = new FileOutputStream(file);
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fos != null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return path;
}
/**
* 刪除圖片
* @param context
* @param bitName
*/
public void deleteFile(Context context,String bitName) {
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
File dirFile = new File(Environment.getExternalStorageDirectory() + File.separator + "images/"+ bitName + ".png");
if (!dirFile.exists()) {
return;
}
dirFile.delete();
} else {
File f = new File(context.getFilesDir() + File.separator
+ "images/" + bitName + ".png");
if(!f.exists()){
return;
}
f.delete();
}
}
}
這里給大家展示一個簡單的拍照,相冊圖片選取,剪輯圖片的樣例demo。
首先創建activity_main.xml布局文件:
<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"
tools:context="${relativePackage}.${activityClass}" >
<Button
android:id="@+id/options"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center"
android:textSize="15sp"
android:text="@string/options_choose" />
<TextView
android:id="@+id/small_img_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:textSize="15sp"/>
<ImageView
android:id="@+id/small_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/app_name" />
<TextView
android:id="@+id/clip_pic_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:textSize="15sp"/>
<ImageView
android:id="@+id/clip_pic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/app_name" />
</LinearLayout>
結合上面的PhotoUtils實現拍照。相冊圖片選取。圖片剪輯功能。
MainActivity.java
package com.syz.photograph;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import com.syz.photograph.ActionSheetDialog.OnSheetItemClickListener;
import com.syz.photograph.ActionSheetDialog.SheetItemColor;
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = MainActivity.class.getSimpleName();
private ImageView smallImg;
private ImageView clipImg;
private TextView tv1,tv2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.options).setOnClickListener(this);
initView();
}
protected void initView() {
smallImg = (ImageView) findViewById(R.id.small_img);
clipImg = (ImageView) findViewById(R.id.clip_pic);
tv1 = (TextView) findViewById(R.id.small_img_title);
tv2 = (TextView) findViewById(R.id.clip_pic_title);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.options) {
options();
}
}
private String path;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == PhotoUtil.NONE)
return;
// 拍照
if (requestCode == PhotoUtil.PHOTOGRAPH) {
// 設置文件保存路徑這里放在跟文件夾下
File picture = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
picture = new File(Environment.getExternalStorageDirectory() + PhotoUtil.imageName);
if (!picture.exists()) {
picture = new File(Environment.getExternalStorageDirectory() + PhotoUtil.imageName);
}
} else {
picture = new File(this.getFilesDir() + PhotoUtil.imageName);
if (!picture.exists()) {
picture = new File(MainActivity.this.getFilesDir() + PhotoUtil.imageName);
}
}
path = PhotoUtil.getPath(this);// 生成一個地址用於存放剪輯后的圖片
if (TextUtils.isEmpty(path)) {
Log.e(TAG, "隨機生成的用於存放剪輯后的圖片的地址失敗");
return;
}
Uri imageUri = UriPathUtils.getUri(this, path);
PhotoUtil.startPhotoZoom(MainActivity.this, Uri.fromFile(picture), PhotoUtil.PICTURE_HEIGHT, PhotoUtil.PICTURE_WIDTH, imageUri);
}
if (data == null)
return;
// 讀取相冊縮放圖片
if (requestCode == PhotoUtil.PHOTOZOOM) {
path = PhotoUtil.getPath(this);// 生成一個地址用於存放剪輯后的圖片
if (TextUtils.isEmpty(path)) {
Log.e(TAG, "隨機生成的用於存放剪輯后的圖片的地址失敗");
return;
}
Uri imageUri = UriPathUtils.getUri(this, path);
PhotoUtil.startPhotoZoom(MainActivity.this, data.getData(), PhotoUtil.PICTURE_HEIGHT, PhotoUtil.PICTURE_WIDTH, imageUri);
}
// 處理結果
if (requestCode == PhotoUtil.PHOTORESOULT) {
/**
* 在這里處理剪輯結果。能夠獲取縮略圖,獲取剪輯圖片的地址。得到這些信息能夠選則用於上傳圖片等等操作
* */
/**
* 如。依據path獲取剪輯后的圖片
*/
Bitmap bitmap = PhotoUtil.convertToBitmap(path,PhotoUtil.PICTURE_HEIGHT, PhotoUtil.PICTURE_WIDTH);
if(bitmap != null){
tv2.setText(bitmap.getHeight()+"x"+bitmap.getWidth()+"圖");
clipImg.setImageBitmap(bitmap);
}
Bitmap bitmap2 = PhotoUtil.convertToBitmap(path,120, 120);
if(bitmap2 != null){
tv1.setText(bitmap2.getHeight()+"x"+bitmap2.getWidth()+"圖");
smallImg.setImageBitmap(bitmap2);
}
// Bundle extras = data.getExtras();
// if (extras != null) {
// Bitmap photo = extras.getParcelable("data");
// ByteArrayOutputStream stream = new ByteArrayOutputStream();
// photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);// (0-100)壓縮文件
// InputStream isBm = new ByteArrayInputStream(stream.toByteArray());
// }
}
super.onActivityResult(requestCode, resultCode, data);
}
protected void options() {
ActionSheetDialog mDialog = new ActionSheetDialog(this).builder();
mDialog.setTitle("選擇");
mDialog.setCancelable(false);
mDialog.addSheetItem("拍照", SheetItemColor.Blue, new OnSheetItemClickListener() {
@Override
public void onClick(int which) {
PhotoUtil.photograph(MainActivity.this);
}
}).addSheetItem("從相冊選取", SheetItemColor.Blue, new OnSheetItemClickListener() {
@Override
public void onClick(int which) {
PhotoUtil.selectPictureFromAlbum(MainActivity.this);
}
}).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
效果圖展示:

拍照+剪輯:


相冊選取+剪輯:


最后附上Demo地址:http://download.csdn.net/detail/loveyaozu/9492321
