安卓头像设置

来源:互联网 发布:机械 simulink 知乎 编辑:程序博客网 时间:2024/06/05 05:54

     基本上,我们在任何一款安卓成熟的APP中都有头像设置这个功能,今天我就是告诉大家这个是怎么实现的。

   首先建个popwindow,然后启动它,选择拍照和或者选取系统照片。

    一.拍照:

    //启动系统的拍照功能                Intent takephoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);                //新建个.jpg文件存放拍照出来的图片                uriTemp = Uri.fromFile(new File(fileTemp, "临时.jpg"));                takephoto.putExtra(MediaStore.EXTRA_OUTPUT, uriTemp);                startActivityForResult(takephoto, photoing);
     二.选取系统文件

 //启动系统给的查询照片功能                Intent pic = new Intent(Intent.ACTION_GET_CONTENT);                //设置成所有照片类型                pic.setType("image/*");                startActivityForResult(pic, looking);                popupWindow.dismiss();

    三.处理数据

   

 @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);        if (resultCode == RESULT_OK) {            switch (requestCode) {                case looking:                    Uri uri = data.getData();                    setBitmap(uri);                    break;                case photoing:                    setBitmap(uriTemp);                    break;            }        }    }
    四.压缩图片

 try {            bitmap = MediaStore.Images.Media.getBitmap(                    this.getContentResolver(), uri);        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        small = PhotoUtil.SizeImage(bitmap);        head.setImageBitmap(small);
    压缩图片的具体工具类

public static Bitmap SizeImage(Bitmap image) {ByteArrayOutputStream os = new ByteArrayOutputStream();image.compress(CompressFormat.JPEG, 100, os);while (os.toByteArray().length / 1024 > 1111) {os.reset();image.compress(CompressFormat.JPEG, 50, os);}ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());BitmapFactory.Options options = new Options();options.inJustDecodeBounds = true;options.inJustDecodeBounds = false;int h = options.outHeight;int w = options.outWidth;int hh = 666;int ww = 666;int b = 1;if (h > w && h > hh) {b = h / hh;} else if (w > h && w > ww) {b = w / ww;}options.inPreferredConfig = Config.RGB_565;options.inSampleSize = b;is = new ByteArrayInputStream(os.toByteArray());        Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);return bitmap;}
由于图片要上传和保留在本地,所以对图片进行压缩。由于两种数据返回的是URI(通用资源标志符),再将URI变成bitmap(位图文件),再将bitmap转为图片格式.png。

五.效果图





原创粉丝点击