现如今好多应用中心,联系人列表等都有头像上传的功能,这篇博客来讲一下它的实现原理
布局如下:
android:layout_width="65dp"
android:layout_height="65dp"
android:layout_gravity="center"
android:layout_marginBottom="8dp"
circleimageView:border_color="#ffffff"
circleimageView:border_width="1dp" />
布局很简单,就是一个自定义的imageview
这里弹出一个对话框,根据选择方式不同调用不同的功能
// 这里item是根据选择的方式,
if (item == 0)
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,
PHOTO_REQUEST_GALLERY);// 调用相机功能
}
else
{
Intent intent = new Intent(// 调用相册
MediaStore.ACTION_IMAGE_CAPTURE);
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED))
{
tempFile = new File(Environment
.getExternalStorageDirectory(),
PHOTO_FILE_NAME);
Uri uri = Uri.fromFile(tempFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent,
PHOTO_REQUEST_CAREMA);
}
else
{
Toast.makeText(MainActivity.this,
"未找到存储卡,无法存储照片!", Toast.LENGTH_SHORT)
.show();
}
}
核心回调方法,根据选择的图片不同,进行回调,将图片携带到头像界面
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PHOTO_REQUEST_GALLERY)
{
if (data != null)
{
Uri uri = data.getData();
Log.e("图片路径??", data.getData() + "");
crop(uri);
}
}
else if (requestCode == PHOTO_REQUEST_CAREMA)
{// 从本地相册获取
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED))
{
crop(Uri.fromFile(tempFile));
}
else
{
Toast.makeText(MainActivity.this, "未找到存储卡,无法存储照片!",
Toast.LENGTH_SHORT).show();
}
}
else if (requestCode == PHOTO_REQUEST_CUT)
{// 图片剪裁后回调
if (data != null)
{
final Bitmap bitmap = data.getParcelableExtra("data");
headIcon.setImageBitmap(bitmap);
// 保存图片到internal storage
FileOutputStream outputStream;
try
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
// out.close();
// final byte[] buffer = out.toByteArray();
// outputStream.write(buffer);
outputStream = MainActivity.this.openFileOutput(
"_head_icon.jpg", Context.MODE_PRIVATE);
out.writeTo(outputStream);
out.close();
outputStream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
try
{
if (tempFile != null && tempFile.exists())
tempFile.delete();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
在裁剪过程中进行照片的数据封装以及回调
private void crop(Uri uri)
{
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 250);
intent.putExtra("outputY", 250);
intent.putExtra("outputFormat", "JPEG");
intent.putExtra("noFaceDetection", true);
intent.putExtra("return-data", true);
startActivityForResult(intent, PHOTO_REQUEST_CUT);
}