[置顶] Android通过访问相机或相册来更换头像
2016-12-29 18:47
471 查看
首先 我们实现的是点击头像 出现一个dialog 选择相机或是相册 来选择照片进行头像更换 这样 由于是自己写的项目 我把有关更换头像的这个class的全部代码都贴在这儿 代码我都备注上了 然后大家自己捡着有用的几个方法 去写 我都有说明 下面看代码
上面的 代码很简单 弹出dialog 三个 按钮 相机 相册 取消 这里xml文件我就不写了 很简单 。。希望对大家有帮助
有一点 sdk版本要22 因为22以上 有的手机调试 相机调不出来 大家注意一下 大家不要忘了把权限加上哦,,,
public class Fragment_Mine extends Fragment { @InjectView(R.id.yonghuming_text) TextView yonghumingText; @InjectView(R.id.drawee_img) SimpleDraweeView draweeImg; private Button btn_picture, btn_photo, btn_cancle; private static String path = "http://192.168.4.188/Goods/app/user/info.json"; private static String uploadpath = "http://192.168.4.188/Goods/app/user/upload.json"; private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照 private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择 private static final int PHOTO_REQUEST_CUT = 3;// 结果 private static final String PHOTO_FILE_NAME = "temp_photo.jpg"; private String facePath; private Handler mHandler = new Handler(); private HashMap<String, String> map; private String selectImaPath; private File imageFile; private Uri uri; private String token; private ArrayList<HashMap<String, Object>> meumList = new ArrayList<HashMap<String, Object>>(); private int image[] = {R.mipmap.gerenxinxi, R.mipmap.wodefabu, R.mipmap.guanzhu, R.mipmap.yaoqingma, R.mipmap.chanpin, R.mipmap.gengxin}; private String text[] = {"个人信息", "我的发布", "我的关注", "我的邀请码", "关于产品", "版本更新"}; private GridView gv; private LinearLayout tuichu; private LinearLayout denglu; private FrameLayout fl; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.mine_layout, container, false); ButterKnife.inject(this, v); tuichu = (LinearLayout) v.findViewById(R.id.tuichu); denglu = (LinearLayout) v.findViewById(R.id.denglu); gv = (GridView) v.findViewById(R.id.gridview); fl = (FrameLayout) v.findViewById(R.id.fragment); update(); gv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { switch (i) { case 0: startActivity(new Intent(getActivity(), GeRenZiLiao.class)); break; case 1: startActivity(new Intent(getActivity(), MyFaBuActivity.class)); break; case 2: startActivity(new Intent(getActivity(), MyGuanZhuActivity.class)); break; case 3: startActivity(new Intent(getActivity(), YaoQIngMa.class)); break; case 4: startActivity(new Intent(getActivity(), GeRenZiLiao.class)); break; case 5: startActivity(new Intent(getActivity(), GeRenZiLiao.class)); break; } } }); map = new HashMap<>(); token = (String) ShareUtils.getData(getActivity(), "token", ""); map.put("token", token); getdata(); facePath = Environment.getExternalStorageDirectory() + "/face.jpg"; return v; } public void update() { for (int i = 0; i < image.length; i++) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("ItemImage", image[i]); map.put("ItemText", text[i]); meumList.add(map); } SimpleAdapter saItem = new SimpleAdapter(getActivity(), meumList, //数据源 R.layout.gridview_item, //xml实现 new String[]{"ItemImage", "ItemText"}, //对应map的Key new int[]{R.id.ItemImage, R.id.ItemText}); //对应R的Id //添加Item到网格中 gv.setAdapter(saItem); } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.reset(this); } @OnClick({R.id.yonghuming_text, R.id.drawee_img}) public void onClick(View view) { switch (view.getId()) { case R.id.yonghuming_text: break; case R.id.drawee_img: showDialog(); break; } } // 点击头像出现的dialog private void showDialog() { View view = getLayoutInflater(getArguments()).inflate(R.layout.dialog_item, null); final Dialog dialog = new Dialog(getActivity(), R.style.transparentFrameWindowStyle); dialog.setContentView( view, new WindowManager.LayoutParams(WindowManager.LayoutParams.FILL_PARENT, ActionBar.LayoutParams.WRAP_CONTENT)); Window window = dialog.getWindow(); // 设置显示动画 window.setWindowAnimations(R.style.main_menu_animstyle); WindowManager.LayoutParams wl = window.getAttributes(); wl.x = 0; wl.y = getActivity().getWindowManager().getDefaultDisplay().getHeight(); // 以下这两句是为了保证按钮可以水平满屏 wl.width = ViewGroup.LayoutParams.MATCH_PARENT; wl.height = ViewGroup.LayoutParams.WRAP_CONTENT; // 设置显示位置 dialog.onWindowAttributesChanged(wl); // 设置点击外围解散 dialog.setCanceledOnTouchOutside(false); dialog.show(); btn_picture = (Button) window.findViewById(R.id.btn_picture); btn_photo = (Button) window.findViewById(R.id.btn_photo); btn_cancle = (Butt b674 on) window.findViewById(R.id.btn_cancle); btn_picture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pictureschose(); dialog.dismiss(); } }); btn_photo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { photo(); dialog.dismiss(); } }); btn_cancle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); } public void getdata() { if (TextUtils.isEmpty(token)) { tuichu.setVisibility(View.GONE); denglu.setVisibility(View.VISIBLE); fl.setVisibility(View.VISIBLE); } else { OkHttpUtils.setGetEntityCallBack(new OkHttpUtils.GetEntityCallBack() { private String photo; private String name; @Override public void getEntity(Object obj) { if (o == null || !(o instanceof GeRenXinXiData)) { return; } GeRenXinXiData geRenXinxi = (GeRenXinXiData) o; name = geRenXinxi.getData().getName(); photo = geRenXinxi.getData().getPhoto(); getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (photo == null || photo.isEmpty()) { draweeImg.setImageResource(R.mipmap.yonghu); }else if (!photo.isEmpty() || photo != null) { String paths = "http://192.168.4.188/Goods/uploads/" + photo; Uri imgurl = Uri.parse(paths); clearCache(imgurl); denglu.setVisibility(View.GONE); fl.setVisibility(View.GONE); draweeImg.setImageURI(imgurl); yonghumingText.setText(name); } } }); } }); OkHttpUtils.post(getActivity(), path, map, GeRenXinXiData.class); } } private void clearCache(Uri imgurl) { // 清除Fresco对这条验证码的缓存 ImagePipeline imagePipeline = Fresco.getImagePipeline(); imagePipeline.evictFromMemoryCache(imgurl); imagePipeline.evictFromDiskCache(imgurl); // combines above two lines imagePipeline.evictFromCache(imgurl); imagePipeline.clearCaches(); } //调用onActivityResult 方法拿到返回的值 @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // 拍照后获取返回值,这里获取到的是原始图片 if (requestCode == PHOTO_REQUEST_CAREMA && resultCode == Activity.RESULT_OK) { mHandler.postDelayed(new Runnable() { @Override public void run() { File file = new File(facePath); Uri uri = Uri.fromFile(file); draweeImg.setImageURI(uri); upLoadFaceIcon(file); } }, 500); } else if (requestCode == PHOTO_REQUEST_GALLERY) { if (data != null) { try { // 获得图片的uri Uri originalUri = data.getData(); selectImaPath = originalUri.toString(); if (selectImaPath.startsWith("file:///s")) { } else { String[] proj = {MediaStore.Images.Media.DATA}; Cursor cursor = getActivity().managedQuery(originalUri, proj, null, null, null); if (cursor != null && cursor.moveToFirst()) { //String string = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)); //按我个人理解 这个是获得用户选择的图片的索引值 int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); //将光标移至开头 ,这个很重要,不小心很容易引起越界 cursor.moveToFirst(); //最后根据索引值获取图片路径 selectImaPath = "file:///" + cursor.getString(column_index); Log.e(TAG, "onActivityResult: " + selectImaPath); } } mHandler.postDelayed(new Runnable() { @Override public void run() { clearCache(Uri.parse(selectImaPath)); requestImage(selectImaPath); String replace = selectImaPath.replace("file://", ""); upLoadFaceIcon(new File(replace)); } }, 500); } catch (Exception e) { System.out.println(e.getMessage()); } } } else if (requestCode == PHOTO_REQUEST_CUT) { draweeImg.setImageURI(imageFile.getAbsolutePath()); } super.onActivityResult(requestCode, resultCode, data); } private void pictureschose() { Intent intent = new Intent(); /* 开启Pictures画面Type设定为image */ intent.setType("image/*"); /* 使用Intent.ACTION_GET_CONTENT这个Action */ intent.setAction(Intent.ACTION_GET_CONTENT); /* 取得相片后返回本画面 */ startActivityForResult(intent, PHOTO_REQUEST_GALLERY); } public void photo() { imageFile = new File(facePath); // 启动系统相机 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // 设置拍照后保存的图片存储在文件中 uri = Uri.fromFile(imageFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); // 启动activity并获取返回数据 startActivityForResult(intent, PHOTO_REQUEST_CAREMA); } //上传图片到服务器 private void upLoadFaceIcon(File file) { PhotoPostUtils.getData(new PhotoPostUtils.GetRegisterData() { @Override public void setRegisterData(Object o) { if (o != null && o instanceof Uphoto) { Uphoto o1 = (Uphoto) o; String status = o1.getStatus(); if ("200".equals(status)) { //Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT).show(); System.out.println("上传成功"); } } } }); PhotoPostUtils.upLoad(file, getActivity(), uploadpath, map, Uphoto.class); } // 图片压缩的方法 private void requestImage(String url) { ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(url)) .setAutoRotateEnabled(true) .build(); PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder() .setImageRequest(request) .build(); draweeImg.setController(controller); } }
上面的 代码很简单 弹出dialog 三个 按钮 相机 相册 取消 这里xml文件我就不写了 很简单 。。希望对大家有帮助
有一点 sdk版本要22 因为22以上 有的手机调试 相机调不出来 大家注意一下 大家不要忘了把权限加上哦,,,
相关文章推荐
- android通过点击ImageView弹出上下文菜单,然后通过访问系统的相册和相机,更换ImageView图片
- Android中通过访问本地相册或者相机设置用户头像
- Android中通过访问本地相册或者相机设置用户头像实例
- Android调用系统相机或相册更换头像
- Android通过系统相机和相册设置头像
- android通过相册、相机设置头像
- Android之圆形头像(实现相机拍摄+相册选择+图片裁剪功能)
- Android 如何通过相册和相机来获取图片
- android调用手机相机、相册,设置头像
- Android选择头像(从相机-相册-截图获取),以及闪退的解决
- Android--利用相机或相册截取用户头像(解决了miui无法截取,以及部分机型拍照无返回Uri)【上】
- 【iOS开发系列】更换头像(相机、相册)
- android中调用系统相机拍照并访问本地相册
- Android webview支持type="file" 打开相机和相册,支持小米(亲测6.0通过)
- android圆形头像:相机裁剪+相册选择
- JS 使用 Android + IOS 相册 + 相机 进行自定义头像 + 限制裁剪后图片尺寸 + base64 string 与 图片互相转换
- Android开发--通过相册或拍照选择头像
- Android开发--通过相册或拍照选择头像
- Android上传头像代码,相机,相册,裁剪
- Android上传头像代码,相机,相册,裁剪