1.点击图片弹出popupwindow对话框
private void showAvatarPop()
{
View view = LayoutInflater.from(this).inflate(R.layout. pop_showavator,
null);
layout_choose =
(RelativeLayout) view.findViewById(R.id.layout_choose );
layout_photo =
(RelativeLayout) view.findViewById(R.id.layout_photo );
layout_photo.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View
arg0) {
ShowLog( "点击拍照" );
// TODO Auto-generated
method stub
layout_choose.setBackgroundColor(getResources().getColor(
R.color. base_color_text_white));
layout_photo.setBackgroundDrawable(getResources().getDrawable(
R.drawable. pop_bg_press));
File dir = new File(BmobConstants.MyAvatarDir );
if (!dir.exists())
{
dir.mkdirs();
}
//http://www.2cto.com/kf/201410/345874.html
// 原图
File file = new File(dir, new SimpleDateFormat("yyMMddHHmmss" )
.format( new Date()));
filePath =
file.getAbsolutePath();// 获取相片的保存路径
Uri imageUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra(MediaStore. EXTRA_OUTPUT,
imageUri);
startActivityForResult(intent,
BmobConstants. REQUESTCODE_UPLOADAVATAR_CAMERA);
}
});
layout_choose.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View
arg0) {
// TODO Auto-generated
method stub
ShowLog( "点击相册" );
layout_photo.setBackgroundColor(getResources().getColor(
R.color. base_color_text_white));
layout_choose.setBackgroundDrawable(getResources().getDrawable(
R.drawable. pop_bg_press));
Intent intent = new Intent(Intent.ACTION_PICK , null);
intent.setDataAndType(
MediaStore.Images.Media. EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent,
BmobConstants. REQUESTCODE_UPLOADAVATAR_LOCATION );
}
});
avatorPop = new PopupWindow(view, mScreenWidth,
600);
avatorPop.setTouchInterceptor(new OnTouchListener()
{
@Override
public boolean onTouch(View
v, MotionEvent event) {
if (event.getAction()
== MotionEvent.ACTION_OUTSIDE )
{
avatorPop.dismiss();
return true ;
}
return false ;
}
});
avatorPop.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
avatorPop.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
avatorPop.setTouchable(true);
avatorPop.setFocusable(true);
avatorPop.setOutsideTouchable(true);
avatorPop.setBackgroundDrawable(new BitmapDrawable());
// 动画效果 从底部弹起
avatorPop.setAnimationStyle(R.style.Animations_GrowFromBottom);
avatorPop.showAtLocation(layout_all ,
Gravity.BOTTOM, 0, 0);
}
2.回调
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
// TODO Auto-generated
method stub
super.onActivityResult(requestCode,
resultCode, data);
switch (requestCode)
{
case BmobConstants.REQUESTCODE_UPLOADAVATAR_CAMERA ://
拍照修改头像
if (resultCode
== RESULT_OK) {
if (!Environment.getExternalStorageState().equals(
Environment. MEDIA_MOUNTED))
{
ShowToast( "SD不可用");
return;
}
isFromCamera = true ;
File file = new File(filePath );
degree =
PhotoUtil.readPictureDegree(file.getAbsolutePath());
Log. i("life", "拍照后的角度:" + degree);
startImageAction(Uri. fromFile(file), 200,
200,
BmobConstants. REQUESTCODE_UPLOADAVATAR_CROP, true);
}
break;
case BmobConstants.REQUESTCODE_UPLOADAVATAR_LOCATION ://
本地修改头像
if (avatorPop != null)
{
avatorPop.dismiss();
}
Uri uri = null;
if (data
== null) {
return;
}
if (resultCode
== RESULT_OK) {
if (!Environment.getExternalStorageState().equals(
Environment. MEDIA_MOUNTED))
{
ShowToast( "SD不可用");
return;
}
isFromCamera = false ;
uri = data.getData();
startImageAction(uri, 200, 200,
BmobConstants. REQUESTCODE_UPLOADAVATAR_CROP, true);
} else {
ShowToast( "照片获取失败" );
}
break;
case BmobConstants.REQUESTCODE_UPLOADAVATAR_CROP ://
裁剪头像返回
// TODO sent
to crop
if (avatorPop != null)
{
avatorPop.dismiss();
}
if (data
== null) {
// Toast.makeText(this,
"取消选择", Toast.LENGTH_SHORT).show();
return;
} else {
saveCropAvator(data);
}
// 初始化文件路径
filePath = "";
// 上传头像
uploadAvatar();
break;
default:
break;
}
}
3.图片的裁剪
private void startImageAction(Uri
uri, int outputX, int outputY,
int requestCode, boolean isCrop)
{
Intent intent = null;
if (isCrop)
{
intent = new Intent("com.android.camera.action.CROP" );
} else {
intent = new Intent(Intent.ACTION_GET_CONTENT , null);
}
intent.setDataAndType(uri, "image/*");
intent.putExtra( "crop", "true" );
intent.putExtra( "aspectX",
1);
intent.putExtra( "aspectY",
1);
intent.putExtra( "outputX",
outputX);
intent.putExtra( "outputY",
outputY);
intent.putExtra( "scale", true );
intent.putExtra(MediaStore. EXTRA_OUTPUT,
uri);
intent.putExtra( "return-data", true );
intent.putExtra( "outputFormat",
Bitmap.CompressFormat.JPEG .toString());
intent.putExtra( "noFaceDetection", true); //
no face detection
startActivityForResult(intent, requestCode);
}
4.保存裁剪的图片
/**
* 保存裁剪的头像
*
* @param data
*/
private void saveCropAvator(Intent
data) {
Bundle extras = data.getExtras();
if (extras
!= null) {
Bitmap bitmap = extras.getParcelable("data" );
Log. i("life", "avatar
- bitmap = " + bitmap);
if (bitmap
!= null) {
bitmap = PhotoUtil.toRoundCorner(bitmap, 10);
if (isFromCamera && degree !=
0) {
bitmap = PhotoUtil.rotaingImageView(degree,
bitmap);
}
iv_set_avator.setImageBitmap(bitmap);
// 保存图片
String filename = new SimpleDateFormat("yyMMddHHmmss" )
.format( new Date())+".png";
path =
BmobConstants. MyAvatarDir +
filename;
PhotoUtil. saveBitmap(BmobConstants.MyAvatarDir,
filename,
bitmap, true);
// 上传头像
if (bitmap
!= null &&
bitmap.isRecycled()) {
bitmap.recycle();
}
}
}
}
4.上传头像
private void uploadAvatar()
{
BmobLog. i("头像地址:" + path);
final BmobFile
bmobFile = new BmobFile(new File(path ));
bmobFile.upload( this, new UploadFileListener()
{
@Override
public void onSuccess()
{
// TODO Auto-generated
method stub
String url = bmobFile.getFileUrl(SetMyInfoActivity.this );
// 更新BmobUser对象
updateUserAvatar(url);
}
@Override
public void onProgress(Integer
arg0) {
// TODO Auto-generated
method stub
}
@Override
public void onFailure(int arg0,
String msg) {
// TODO Auto-generated
method stub
ShowToast( "头像上传失败:" +
msg);
}
});
}
private void updateUserAvatar(final String
url) {
User u = new User();
u.setAvatar(url);
updateUserData(u, new UpdateListener()
{
@Override
public void onSuccess()
{
// TODO Auto-generated
method stub
ShowToast( "头像更新成功!" );
// 更新头像
refreshAvatar(url);
}
@Override
public void onFailure(int code,
String msg) {
// TODO Auto-generated
method stub
ShowToast( "头像更新失败:" +
msg);
}
});
}
private void updateUserData(User
user,UpdateListener listener){
User current = (User) userManager.getCurrentUser(User.class);
user.setObjectId(current.getObjectId());
user.update( this,
listener);
}
}
/**
* 更新头像 refreshAvatar
*
* @return void
* @throws
*/
private void refreshAvatar(String
avatar) {
if (avatar
!= null &&
!avatar.equals("" )) {
ImageLoader. getInstance().displayImage(avatar, iv_set_avator,
ImageLoadOptions. getOptions());
} else {
iv_set_avator.setImageResource(R.drawable.default_head);
}
}
用到的工具类
package com.bmob.im.demo.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
public class PhotoUtil {
/**
* 回收垃圾 recycle
*
* @throws
*/
public static void recycle(Bitmap bitmap) {
// 先判断是否已经回收
if (bitmap != null && !bitmap.isRecycled()) {
// 回收并且置为null
bitmap.recycle();
bitmap = null;
}
System.gc();
}
/**
* 获取指定路径下的图片的指定大小的缩略图 getImageThumbnail
*
* @return Bitmap
* @throws
*/
public static Bitmap getImageThumbnail(String imagePath, int width,
int height) {
Bitmap bitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// 获取这个图片的宽和高,注意此处的bitmap为null
bitmap = BitmapFactory.decodeFile(imagePath, options);
options.inJustDecodeBounds = false; // 设为 false
// 计算缩放比
int h = options.outHeight;
int w = options.outWidth;
int beWidth = w / width;
int beHeight = h / height;
int be = 1;
if (beWidth < beHeight) {
be = beWidth;
} else {
be = beHeight;
}
if (be <= 0) {
be = 1;
}
options.inSampleSize = be;
// 重新读入图片,读取缩放后的bitmap,注意这次要把options.inJustDecodeBounds 设为 false
bitmap = BitmapFactory.decodeFile(imagePath, options);
// 利用ThumbnailUtils来创建缩略图,这里要指定要缩放哪个Bitmap对象
bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
return bitmap;
}
/**
* saveBitmap
*
* @param @param filename---完整的路径格式-包含目录以及文件名
* @param @param bitmap
* @param @param isDelete --是否只留一张
* @return void
* @throws
*/
public static void saveBitmap(String dirpath, String filename,
Bitmap bitmap, boolean isDelete) {
File dir = new File(dirpath);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dirpath, filename);
// 若存在即删除-默认只保留一张
if (isDelete) {
if (file.exists()) {
file.delete();
}
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
out.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static File getFilePath(String filePath, String fileName) {
File file = null;
makeRootDirectory(filePath);
try {
file = new File(filePath + fileName);
if (!file.exists()) {
file.createNewFile();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
public static void makeRootDirectory(String filePath) {
File file = null;
try {
file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
} catch (Exception e) {
}
}
/**
*
* 读取图片属性:旋转的角度
* @param path 图片绝对路径
* @return degree旋转的角度
*/
public static int readPictureDegree(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;
}
/** 旋转图片一定角度
* rotaingImageView
* @return Bitmap
* @throws
*/
public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
// 旋转图片 动作
Matrix matrix = new Matrix();
matrix.postRotate(angle);
// 创建新的图片
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizedBitmap;
}
/**
* 将图片变为圆角
*
* @param bitmap
* 原Bitmap图片
* @param pixels
* 图片圆角的弧度(单位:像素(px))
* @return 带有圆角的图片(Bitmap 类型)
*/
public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
/**
* 将图片转化为圆形头像
*
* @Title: toRoundBitmap
* @throws
*/
public static Bitmap toRoundBitmap(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float roundPx;
float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
if (width <= height) {
roundPx = width / 2;
left = 0;
top = 0;
right = width;
bottom = width;
height = width;
dst_left = 0;
dst_top = 0;
dst_right = width;
dst_bottom = width;
} else {
roundPx = height / 2;
float clip = (width - height) / 2;
left = clip;
right = width - clip;
top = 0;
bottom = height;
width = height;
dst_left = 0;
dst_top = 0;
dst_right = height;
dst_bottom = height;
}
Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect src = new Rect((int) left, (int) top, (int) right,
(int) bottom);
final Rect dst = new Rect((int) dst_left, (int) dst_top,
(int) dst_right, (int) dst_bottom);
final RectF rectF = new RectF(dst);
paint.setAntiAlias(true);// 设置画笔无锯齿
canvas.drawARGB(0, 0, 0, 0); // 填充整个Canvas
// 以下有两种方法画圆,drawRounRect和drawCircle
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);// 画圆角矩形,第一个参数为图形显示区域,第二个参数和第三个参数分别是水平圆角半径和垂直圆角半径。
// canvas.drawCircle(roundPx, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));// 设置两张图片相交时的模式,参考http://trylovecatch.iteye.com/blog/1189452
canvas.drawBitmap(bitmap, src, dst, paint); // 以Mode.SRC_IN模式合并bitmap和已经draw了的Circle
return output;
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
public class PhotoUtil {
/**
* 回收垃圾 recycle
*
* @throws
*/
public static void recycle(Bitmap bitmap) {
// 先判断是否已经回收
if (bitmap != null && !bitmap.isRecycled()) {
// 回收并且置为null
bitmap.recycle();
bitmap = null;
}
System.gc();
}
/**
* 获取指定路径下的图片的指定大小的缩略图 getImageThumbnail
*
* @return Bitmap
* @throws
*/
public static Bitmap getImageThumbnail(String imagePath, int width,
int height) {
Bitmap bitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// 获取这个图片的宽和高,注意此处的bitmap为null
bitmap = BitmapFactory.decodeFile(imagePath, options);
options.inJustDecodeBounds = false; // 设为 false
// 计算缩放比
int h = options.outHeight;
int w = options.outWidth;
int beWidth = w / width;
int beHeight = h / height;
int be = 1;
if (beWidth < beHeight) {
be = beWidth;
} else {
be = beHeight;
}
if (be <= 0) {
be = 1;
}
options.inSampleSize = be;
// 重新读入图片,读取缩放后的bitmap,注意这次要把options.inJustDecodeBounds 设为 false
bitmap = BitmapFactory.decodeFile(imagePath, options);
// 利用ThumbnailUtils来创建缩略图,这里要指定要缩放哪个Bitmap对象
bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
return bitmap;
}
/**
* saveBitmap
*
* @param @param filename---完整的路径格式-包含目录以及文件名
* @param @param bitmap
* @param @param isDelete --是否只留一张
* @return void
* @throws
*/
public static void saveBitmap(String dirpath, String filename,
Bitmap bitmap, boolean isDelete) {
File dir = new File(dirpath);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dirpath, filename);
// 若存在即删除-默认只保留一张
if (isDelete) {
if (file.exists()) {
file.delete();
}
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
out.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static File getFilePath(String filePath, String fileName) {
File file = null;
makeRootDirectory(filePath);
try {
file = new File(filePath + fileName);
if (!file.exists()) {
file.createNewFile();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
public static void makeRootDirectory(String filePath) {
File file = null;
try {
file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
} catch (Exception e) {
}
}
/**
*
* 读取图片属性:旋转的角度
* @param path 图片绝对路径
* @return degree旋转的角度
*/
public static int readPictureDegree(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;
}
/** 旋转图片一定角度
* rotaingImageView
* @return Bitmap
* @throws
*/
public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
// 旋转图片 动作
Matrix matrix = new Matrix();
matrix.postRotate(angle);
// 创建新的图片
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizedBitmap;
}
/**
* 将图片变为圆角
*
* @param bitmap
* 原Bitmap图片
* @param pixels
* 图片圆角的弧度(单位:像素(px))
* @return 带有圆角的图片(Bitmap 类型)
*/
public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
/**
* 将图片转化为圆形头像
*
* @Title: toRoundBitmap
* @throws
*/
public static Bitmap toRoundBitmap(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float roundPx;
float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
if (width <= height) {
roundPx = width / 2;
left = 0;
top = 0;
right = width;
bottom = width;
height = width;
dst_left = 0;
dst_top = 0;
dst_right = width;
dst_bottom = width;
} else {
roundPx = height / 2;
float clip = (width - height) / 2;
left = clip;
right = width - clip;
top = 0;
bottom = height;
width = height;
dst_left = 0;
dst_top = 0;
dst_right = height;
dst_bottom = height;
}
Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect src = new Rect((int) left, (int) top, (int) right,
(int) bottom);
final Rect dst = new Rect((int) dst_left, (int) dst_top,
(int) dst_right, (int) dst_bottom);
final RectF rectF = new RectF(dst);
paint.setAntiAlias(true);// 设置画笔无锯齿
canvas.drawARGB(0, 0, 0, 0); // 填充整个Canvas
// 以下有两种方法画圆,drawRounRect和drawCircle
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);// 画圆角矩形,第一个参数为图形显示区域,第二个参数和第三个参数分别是水平圆角半径和垂直圆角半径。
// canvas.drawCircle(roundPx, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));// 设置两张图片相交时的模式,参考http://trylovecatch.iteye.com/blog/1189452
canvas.drawBitmap(bitmap, src, dst, paint); // 以Mode.SRC_IN模式合并bitmap和已经draw了的Circle
return output;
}
}
本文介绍了一个Android应用中实现头像选择、裁剪及上传功能的具体代码实现。包括通过相机拍摄或相册选取头像,进行裁剪并上传至服务器的过程。
2947

被折叠的 条评论
为什么被折叠?



