安卓头像设置

本文介绍如何在安卓应用中实现头像设置功能,包括通过系统相机拍照、从相册选择图片、处理返回数据及图片压缩等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     基本上,我们在任何一款安卓成熟的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。

五.效果图





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值