Android下头像选择

protected void setUserHeadIcon() {
AlertDialog pickpicDialog = new AlertDialog.Builder(mContext)
.setTitle("选择图片来源")
.setItems(R.array.choosepic,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
switch (which) {
case 0:
Intent ti = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
ContentValues values = new ContentValues();
iconUri = getContentResolver()
.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
ti.putExtra(MediaStore.EXTRA_OUTPUT,
iconUri);
startActivityForResult(ti, TAKEPHOTO);
break;
case 1:
Intent intent = new Intent(
Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(
intent,
getResources()
.getString(
R.string.choose_pic)),
CHOOSEIMAGE);
break;
case 2:
break;
}
}
}).create();
pickpicDialog.show();

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case TAKEPHOTO:
ContentResolver cr = getContentResolver();
Cursor cursor_create = cr
.query(iconUri, null, null, null, null);
cursor_create.moveToFirst();
String pathString = "";
if (cursor_create != null) {
pathString = cursor_create.getString(1);
}
cursor_create.close();
Log.i("path", pathString);
Bitmap nBitmap = ImageUtil.comp(pathString, width, height);
WeakReference<Bitmap> weakRerference = new WeakReference<Bitmap>(
nBitmap);
File file = new File(pathString);
iconUrl = saveImageToSD(weakRerference.get(),
ImageUtil.rename(file));
uploadHeadIcon(iconUrl);
break;


case CHOOSEIMAGE:
Uri tu = data.getData();
Cursor cursor = getContentResolver().query(tu, null, null,
null, null);
cursor.moveToFirst();
String imgPath = cursor.getString(1);
cursor.close();


try {
Bitmap bm = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imgPath, options);
int width = options.outWidth;
int height = options.outHeight;
if (width <= 56 || height <= 56) {
bm = BitmapFactory.decodeFile(imgPath);
} else {
if (width > 500) {
options.inSampleSize = 5;
} else if (width > 130 && width < 500) {
options.inSampleSize = 2;
}
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(imgPath, options);
}
// Bitmap bitmap = ImageUtil.getCuttedBitmap(imgPath, bm);
WeakReference<Bitmap> wf = new WeakReference<Bitmap>(bm);
File file2 = new File(imgPath);
iconUrl = saveImageToSD(wf.get(), ImageUtil.rename(file2));
uploadHeadIcon(iconUrl);
} catch (Exception ex) {
Log.e("set headicon", "### " + ex.getMessage());
}
break;

}


private String saveImageToSD(Bitmap bitmap, String icon_name) {
// 保存入sdCard
File file = new File(Constants.picRootPath + icon_name);
Log.i("icon url", file.getPath());
try {
FileOutputStream out = new FileOutputStream(file);
if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return file.getPath();
}

public class ImageUtil {
public static int getCameraImgRotateDegree(String path) {
   int degree = 0;
   ExifInterface exif;
   try {
     exif = new ExifInterface(path);
     int orientation  = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
     
     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) {
     Log.e("getCameraImgRotateDegree() error", e.getMessage());
     e.printStackTrace();
   }
   
   return degree;
 }
public static Bitmap getCuttedBitmap(String path) { 
BitmapFactory.Options opts = new BitmapFactory.Options();
         opts.inJustDecodeBounds = true;
        // opts.inSampleSize = 5;
         Bitmap b = BitmapFactory.decodeFile(path, opts);
   int degree = ImageUtil.getCameraImgRotateDegree(path);
   int sWidth = opts.outWidth; 
   int sHeight = opts.outHeight;
   int nWidth = 0;
   int nHeight = 0;
   int x = 0;
   int y = 0;
   if (sWidth > sHeight) {
     nWidth = sHeight;
     nHeight = sHeight;
     x = (sWidth - sHeight) / 2;
     y = 0;
   } else {
     nWidth = sWidth;
     nHeight = sWidth;
     x = 0;
     y = (sHeight - sWidth) / 2;
   }
   Matrix matrix = new Matrix();
   matrix.postRotate(degree);
   Bitmap newBitmap = Bitmap.createBitmap(b, x, y, nWidth, nHeight, matrix, true);
   if (sWidth <= 56 || sHeight <= 56) {
     return newBitmap;
   }
   try {
     newBitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream(new File("/sdcard/egg/head_icon_temp.png")));
   }
   catch (FileNotFoundException e) {
     e.printStackTrace();
     return null;
   } 
   int destWidth = 56;
   int destHeight = 56;
   int ratio = nWidth / destWidth + 1;
   BitmapFactory.Options options = new BitmapFactory.Options();
   options.inSampleSize = ratio;
   options.inJustDecodeBounds = false;
   options.outWidth = destWidth;
   options.outHeight = destHeight;
   
   Bitmap destBitmap = BitmapFactory.decodeFile("/sdcard/egg/head_icon_temp.png", options);
   
   try {
     destBitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream(new File(Constants.iconRootPath)));
     return destBitmap;
   }
   catch (FileNotFoundException e) {
     e.printStackTrace();
     
     return null;
   } finally {
     newBitmap.recycle();
     newBitmap = null;
   }
 }

//生成文件的唯一标记名
public static String rename(File file) {
int index=file.getName().lastIndexOf(".");
String body=file.getName().substring(0,index);
String body_value = "";
try {
body_value = new String(body.getBytes(),"UTF-8");
Log.i("file name", body_value);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}  
String postfix="";
String timer="";
if(index!=-1){
timer=new Date().getTime()+"";
postfix=file.getName().substring(index);
}
else{
timer=new Date().getTime()+"";
postfix="";
}
String newFileName=body+timer+postfix;
Log.i("new file name", newFileName);
return newFileName;
}
public static void setLocalImageView(String path, ImageView imgView) {
   if (BitmapCacheStore.getBitmap(path) == null) {
     SoftReference<Bitmap> bitmap = new SoftReference<Bitmap>(BitmapFactory.decodeFile(path));
     BitmapCacheStore.addBitmap(path, bitmap);
     Bitmap cBitmap = createFramedPhoto(56, 56, bitmap.get(), 6);
     imgView.setImageBitmap(cBitmap);
   } else {
    Bitmap cBitmap = createFramedPhoto(56, 56, BitmapCacheStore.getBitmap(path).get(), 6);
     imgView.setImageBitmap(cBitmap);
     //imgView.setImageBitmap(BitmapCacheStore.getBitmap(path).get());
   }
 }
public static void setDefaultAvatar(Context context, ImageView imgView) {
   if (BitmapCacheStore.getBitmap(BitmapCacheStore.DEFAULT_AVATAR) == null) {
     SoftReference<Bitmap> bitmap = new SoftReference<Bitmap>(BitmapFactory.decodeResource(context.getResources(), R.drawable.default_avatar_shadow));
     BitmapCacheStore.addBitmap(BitmapCacheStore.DEFAULT_AVATAR, bitmap);
   }
   
   imgView.setImageBitmap(BitmapCacheStore.getBitmap(BitmapCacheStore.DEFAULT_AVATAR).get());
 }
// get middle size png.
 public static Bitmap getMiddleSizeBitmap(Context context,String fPath) {
   float density = context.getResources().getDisplayMetrics().density;
   Bitmap result = null;
   int degree = ImageUtil.getCameraImgRotateDegree(fPath);
   
   File f = new File(fPath);
   BitmapFactory.Options opts = new BitmapFactory.Options();
   
   if (512000 < f.length() && f.length() <= 819200) { // 300-800k
     opts.inSampleSize = 1;
   } else if (819200 < f.length() && f.length() <= 1048576) { // 800-1024k
     opts.inSampleSize = 2;
   } else if (1048576 < f.length() && f.length() <= 1636000){ // 1M - 1.5M 
     opts.inSampleSize = 4;
   } else if (1636000 < f.length() && f.length() <= 2097152) {// 
     opts.inSampleSize = 6;
   } else if (f.length() > 2097152) {
     opts.inSampleSize = 8;
   } else {
     opts.inSampleSize = 1;
   }
   Bitmap bitmap = BitmapFactory.decodeFile(f.getPath(), opts);
   
   int sWidth = bitmap.getWidth(); 
   int sHeight = bitmap.getHeight();
   int x = 0;
   int y = 0;
   
   Matrix matrix = new Matrix();
   matrix.postRotate(degree);
   
   result = Bitmap.createBitmap(bitmap, x, y, sWidth, sHeight, matrix, true);


   try {
     result.compress(CompressFormat.PNG, 100, new FileOutputStream(getMiddleSizePicPath(fPath)));
   }
   catch (FileNotFoundException e) {
     e.printStackTrace();
     
     return null;
   }
   
   return result; 
   
 }
 
 public static String getMiddleSizePicPath(String path) {
   StringBuffer buffer = new StringBuffer();
   
   int sIndex = path.lastIndexOf("/");
   int rIndex = path.lastIndexOf(".");
   buffer.append(Constants.picRootPath);
buffer.append("/");
buffer.append(path.subSequence(sIndex + 1, rIndex));
buffer.append(".");
buffer.append(path.subSequence(rIndex + 1, path.length()));
   return buffer.toString();
 }
 
//压缩图片成路径
private String compressPic(String path){
//对图片进行压缩  
BitmapFactory.Options options = new BitmapFactory.Options();  
options.inJustDecodeBounds = true;  
//获取这个图片的宽和高  
Bitmap bitmap = BitmapFactory.decodeFile(path,options);//此时返回bm为空  
options.inJustDecodeBounds =false;  
//计算缩放比  
int be = (int)(options.outHeight / (float)200);  
   if(be <= 0)  
    be =1;  
options.inSampleSize =be;  
//重新读入图片,注意这次要把options.inJustDecodeBounds设为false哦  
bitmap = BitmapFactory.decodeFile(path,options);  
int w = bitmap.getWidth();  
int h=bitmap.getHeight();  
System.out.println(w+" "+h);  
/* myImageView.setImageBitmap(bitmap);  
//保存入sdCard  
File file2= new File(path);  
try {  
  FileOutputStream out = new FileOutputStream(file2);  
    if(bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)){  
           out.flush();  
           out.close();  
            }  
} catch (Exception e) { */
return null; 
}  
//压缩图片成路径
public static Bitmap compressPicToBitMap(String path){
//对图片进行压缩  
BitmapFactory.Options options = new BitmapFactory.Options();  
options.inJustDecodeBounds = true;  
//获取这个图片的宽和高  
Bitmap bitmap = BitmapFactory.decodeFile(path,options);//此时返回bm为空  
options.inJustDecodeBounds =false;  
//计算缩放比  
int be = (int)(options.outHeight / (float)200);  
if(be <= 0)  
be =1;  
options.inSampleSize =be;  
//重新读入图片,注意这次要把options.inJustDecodeBounds设为false哦  
bitmap = BitmapFactory.decodeFile(path,options);  
int w = bitmap.getWidth();  
int h=bitmap.getHeight();  
System.out.println(w+" "+h);  
/* myImageView.setImageBitmap(bitmap);  
//保存入sdCard  
File file2= new File(path);  
try {  
  FileOutputStream out = new FileOutputStream(file2);  
    if(bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)){  
           out.flush();  
           out.close();  
           }  
} catch (Exception e) { */
return bitmap; 
}  
//不进行压缩
public static Bitmap getPicToBitMap(String path){
//对图片进行压缩  
BitmapFactory.Options options = new BitmapFactory.Options();  
options.inJustDecodeBounds = true;  
//获取这个图片的宽和高  
Bitmap bitmap = BitmapFactory.decodeFile(path,options);//此时返回bm为空  
options.inJustDecodeBounds =false;  
//计算缩放比  
int be = (int)(options.outHeight / (float)200);  
if(be <= 0)  
be =1;  
options.inSampleSize =be;  
//重新读入图片,注意这次要把options.inJustDecodeBounds设为false哦  
bitmap = BitmapFactory.decodeFile(path,options);  
int w = bitmap.getWidth();  
int h=bitmap.getHeight();  
System.out.println(w+" "+h);  
/* myImageView.setImageBitmap(bitmap);  
//保存入sdCard  
File file2= new File(path);  
try {  
  FileOutputStream out = new FileOutputStream(file2);  
    if(bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)){  
           out.flush();  
           out.close();  
           }  
} catch (Exception e) { */
return bitmap; 
}
public static Bitmap comp(String path,int width,int height) {  
BitmapFactory.Options newOpts = new BitmapFactory.Options();  
newOpts.inJustDecodeBounds = true;  
Bitmap bitmap = BitmapFactory.decodeFile(path,newOpts); 
newOpts.inJustDecodeBounds =false;  
int w = newOpts.outWidth;  
int h = newOpts.outHeight;  


  float hh = height;  
  float ww = width;   
  int be = 1;//be=1表示不缩放   
  if (w > h && w > ww) {
      be = (int) (newOpts.outWidth / ww);  
  } else if (w < h && h > hh) {
       be = (int) (newOpts.outHeight / hh);  
   }  
  if (be <= 0) { 
      be = 1;
  }
   newOpts.inSampleSize = be;//设置缩放比例   
  //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了   
   bitmap = BitmapFactory.decodeFile(path, newOpts);  
  return compressImage(bitmap);//压缩好比例大小后再进行质量压缩   

public static Bitmap compressImage(Bitmap image) {  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    image.compress(Bitmap.CompressFormat.JPEG, 20, baos);
     int options = 100;  
     while ( (baos.toByteArray().length/1024)>10) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩          
        baos.reset();//重置baos即清空baos   
        image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中 
        Log.i("bos length", baos.toByteArray().length + "###############");
        options -= 10;//每次都减少10   
      }  
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
    return bitmap;  


/**
 * @param y 图像的高度
 * @param image 源图片
 * @param outerRadiusRat 圆角的大小
 * @return 圆角图片
 */


public static Bitmap createFramedPhoto(int x, int y, Bitmap bitmap, float outerRadiusRat) {
   //根据源文件新建一个darwable对象
   Drawable imageDrawable = new BitmapDrawable(bitmap);
   // 新建一个新的输出图片
    Bitmap output = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888);
     Canvas canvas = new Canvas(output);
    // 新建一个矩形
  RectF outerRect = new RectF(0, 0, x, y);
    // 产生一个红色的圆角矩形
   Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(Color.RED);
    canvas.drawRoundRect(outerRect, outerRadiusRat, outerRadiusRat, paint);
    // 将源图片绘制到这个圆角矩形上
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
     imageDrawable.setBounds(0, 0, x, y);
     canvas.saveLayer(outerRect, paint, Canvas.ALL_SAVE_FLAG);
          imageDrawable.draw(canvas);


     canvas.restore();
      return output;


 }




}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值