1.我實(shí)現(xiàn)的效果
a:從相冊選擇圖片
b:圖片裁剪
c:保存圖片到本地
d:再次進(jìn)入顯示圖片
2.使用到的依賴
compile 'com.jph.takephoto:takephoto_library:4.0.3'
該依賴的github地址:https://github.com/crazycodeboy/TakePhoto
3.該依賴的示例,寫的挺詳細(xì),
其中MainActivity是選擇fragment還是Activity.我這里選擇的是Activity,其中SimpleActivity是拿到圖片的,只不過示例是在ResultActivity里面展示的暑塑。而對圖片的壓縮裁剪等都是在CustomHelper里面進(jìn)行操作的。這里提供了壓縮裁剪工具等的選擇锅必,而我在項(xiàng)目中是寫死的事格,因?yàn)槲也恍枰x擇。
4.在以上基礎(chǔ)上搞隐,我進(jìn)行了修改驹愚。
a. 新建PhotoHelper類,用于獲得圖片的處理方式劣纲。
public class PhotoHelper {
private View rootView;
public PhotoHelper(View rootView) {
this.rootView = rootView;
}
public static PhotoHelper of(View rootView,Context context){
return new PhotoHelper(rootView);
}
public void onClick(View view, TakePhoto photo){
File file=new File(Environment.getExternalStorageDirectory(),
"/temp"+ System.currentTimeMillis()+".jpg");
if (!file.getParentFile().exists())file.getParentFile().mkdirs();
Uri imageUri=Uri.fromFile(file);
configCompress(photo);
configTakePhotoOption(photo);
photo.onPickFromGalleryWithCrop(imageUri,getCropOptions());
}
//裁剪圖片屬性
private CropOptions getCropOptions() {
CropOptions.Builder builder=new CropOptions.Builder();
builder.setAspectX(800).setAspectY(800);//裁剪時(shí)的尺寸比例
builder.setWithOwnCrop(true);//s使用第三方還是takephoto自帶的裁剪工具
return builder.create();
}
//配置圖片屬性
private void configTakePhotoOption(TakePhoto photo) {
TakePhotoOptions.Builder builder=new TakePhotoOptions.Builder();
builder.setWithOwnGallery(true);//使用自帶相冊
builder.setCorrectImage(false);//糾正旋轉(zhuǎn)角度
photo.setTakePhotoOptions(builder.create());
}
// 配置壓縮
private void configCompress(TakePhoto takePhoto){
CompressConfig config=new CompressConfig.Builder()
.setMaxSize(102400)//大小不超過100k
.setMaxPixel(800)//最大像素800
.enableReserveRaw(true)//是否壓縮
.create();
takePhoto.onEnableCompress(config,true);//這個trued代表顯示壓縮進(jìn)度條
}
}
在onClick方法中逢捺,調(diào)用配置的各種屬性。
b. MainActivity用于展示圖片癞季。首先MainActivity要繼承TakePhotoActivity劫瞳,并重寫TakePhotoActivity里面的幾個方法。
public class MainActivity extends TakePhotoActivity {
private static final String TAG = "MainActivity";
ImageView img;
Button button;
String path;
Bitmap bitmap;
PhotoHelper photoHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView= LayoutInflater.from(this).inflate(R.layout.activity_main,null);
setContentView(contentView);
photoHelper=PhotoHelper.of(contentView,this);
button= (Button) contentView.findViewById(R.id.btn);
img= (ImageView) contentView.findViewById(R.id.img);
if (MyUtils.getBitmap(this)!=null){
img.setImageBitmap(MyUtils.getBitmap(this));
}
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//這步由于封裝就直接進(jìn)入選擇圖片界面了绷柒。
photoHelper.onClick(view,getTakePhoto());
}
});
}
@Override
public void takeCancel() {
super.takeCancel();
}
@Override
public void takeFail(TResult result, String msg) {
super.takeFail(result, msg);
}
@Override
public void takeSuccess(TResult result) {
super.takeSuccess(result);
showImg(result.getImages());
}
private void showImg(final ArrayList<TImage> images) {
Log.e(TAG, "showImg: "+images.get(images.size() - 1).getCompressPath());
path=images.get(images.size() - 1).getCompressPath();
Picasso.with(this).load(new File(path))
.into(img);
new Thread(new Runnable() {
@Override
public void run() {
try {
bitmap = Picasso.with(getApplicationContext())
.load(new File(path))
.resize(MyUtils.dpToPx(getApplicationContext(),200),MyUtils.dpToPx(getApplicationContext(),200))
.transform(new CircleTransform())
.get();
} catch (IOException e) {
e.printStackTrace();
}
if (bitmap!=null){
Log.e(TAG, "run: "+"bitmap不為空志于,進(jìn)行保存" );
MyUtils.savaImage(getApplication(),bitmap);
}
}
}).start();
}
}
這里面關(guān)鍵的地方
一個是在按鈕的監(jiān)聽事件里面調(diào)用之前圖片處理方式的配置,
一個是takeSuccess方法里面調(diào)用展示圖片的方法废睦。
本來使用picasso伺绽,可以直接展示圖片的,但為了能下次進(jìn)入可以直接顯示圖片,我使用picasso將圖片地址轉(zhuǎn)換成bitmap奈应,并保存在sd卡中澜掩。
c. 這是保存圖片以及獲取圖片的一個工具類
public class MyUtils {
private static final String TAG = "MyUtils";
public static String fileDir;
public static File file;
// 根據(jù)filePath獲得bitmap
public static Bitmap getBitmap(Context c){
String filePath=c.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
.getAbsolutePath()+ File.separator+"head.jpg";
Log.e(TAG, "getBitmap: "+filePath );
Bitmap bitmap= BitmapFactory.decodeFile(filePath);
return bitmap;
}
public static int dpToPx(Context context, int dp) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
// 保存圖片
public static void savaImage(Context c,Bitmap bitmap) {
fileDir=c.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath();
Log.e(TAG, "savaImage: "+fileDir);
file= new File(fileDir,"head.jpg");
Log.e(TAG, "savaImage: "+file.toString() );
if (file.exists()){
file.delete();
}
try {
FileOutputStream out=new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,100,out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
d.這是一個使用picasso把圖片變圓形的方法。
public class CircleTransform implements Transformation {
@Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
if (squaredBitmap != source) {
source.recycle();
}
Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader = new BitmapShader(squaredBitmap,
BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
paint.setShader(shader);
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
squaredBitmap.recycle();
return bitmap;
}
@Override
public String key() {
return "circle";
}
}
5.總結(jié)
安卓手機(jī)具有多樣化的圖片裁剪方式和獲取圖片的方法杖挣,很難做到使用系統(tǒng)自帶的方法完美適配各種手機(jī)输硝。于是使用封裝的相冊便是一個很好的選擇。