工作日志记录:调用系统裁剪功能,并裁剪头像之后设为用户头像。
上图:
惯例上代码:
package com.xuganwen.sharesdk;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private Button btn;
private ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.btn);
image=(ImageView)findViewById(R.id.image);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
//intent.setAction(Intent.ACTION_GET_CONTENT);
MainActivity.this.startActivityForResult(intent,100);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 100:
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(data.getData(), "image/*");
// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
// intent.putExtra("scale", true); //保留比例
startActivityForResult(intent, 3);
break;
case 3:
if (data != null) {
/*Bundle extras = data.getExtras();
if (extras != null) {
Bitmap bitmap = (Bitmap) extras.get("data");
String path = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date
());
String picUrl = saveAndgetMyBitmap(path, bitmap);
setImg();
new MyTask().execute();
}*/
Bundle bundle=data.getExtras();
Bitmap bitmap=(Bitmap)bundle.get("data");
image.setImageBitmap(bitmap);
//image.invalidate();
}
break;
}
}
public static String saveAndgetMyBitmap(String bitName, Bitmap mBitmap) {
File file = null;
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
file = new File(Environment.getExternalStorageDirectory(), bitName + ".jpg");
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
try {
fOut.flush();
}
catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
}
catch (IOException e) {
e.printStackTrace();
}
// File file = new File(path);
// path = file.getPath().toString();
}
return file.getAbsolutePath().toString();
}
}