当前位置: 移动技术网 > IT编程>移动开发>Android > Android个人中心的头像上传,图片编码及截取实例

Android个人中心的头像上传,图片编码及截取实例

2019年07月24日  | 移动技术网IT编程  | 我要评论

男子草丛发现异物 捅破后被吓走,怀孕七个月胎儿图,雀金裘一怒倾天下

首先需要有网络权限,然后我们这里匹配的网络请求是之前封装好的okhttp。

非常的简单方便,直接复制进去,依赖一下包,然后调用方法即可。

这里是把图片转换成base64.decode(imagestring, base64.default);

转成base64编码上传。具体内容也不少,需要完全整明白,还是要花点时间慢慢看的。

先看看简单的效果图:

这里写图片描述
这里写图片描述

这里写图片描述
这里写图片描述

那么万事具备,只欠东风了。直接上代码:

public class mainactivity extends appcompatactivity implements view.onclicklistener {

  private imageview iv_img;
  private button bt_camera;
  private button bt_xiangce;
  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 file tempfile;

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    //加载控件
    initview();
  }

  private void initview() {
    iv_img = (imageview) findviewbyid(r.id.iv_img);
    bt_camera = (button) findviewbyid(r.id.bt_camera);
    bt_xiangce = (button) findviewbyid(r.id.bt_xiangce);
    //从sharedpreferences获取图片
    getbitmapfromsharedpreferences();
    //监听两个按钮,相册按钮和相机按钮
    bt_camera.setonclicklistener(this);
    bt_xiangce.setonclicklistener(this);
  }

  @override
  public void onclick(view v) {
    switch (v.getid()) {
      case r.id.bt_camera:
        // 激活相机
        intent intent = new intent("android.media.action.image_capture");
        // 判断存储卡是否可以用,可用进行存储
        if (hassdcard()) {
          tempfile = new file(environment.getexternalstoragedirectory(), photo_file_name);
          // 从文件中创建uri
          uri uri = uri.fromfile(tempfile);
          intent.putextra(mediastore.extra_output, uri);
        }
        // 开启一个带有返回值的activity,请求码为photo_request_carema
        startactivityforresult(intent, photo_request_carema);
        break;
      case r.id.bt_xiangce:
        // 激活系统图库,选择一张图片
        intent intent1 = new intent(intent.action_pick);
        intent1.settype("image/*");
        // 开启一个带有返回值的activity,请求码为photo_request_gallery
        startactivityforresult(intent1, photo_request_gallery);
        break;
    }
  }
  /*
   * 判断sdcard是否被挂载
   */
  private boolean hassdcard() {
    //判断sd卡手否是安装好的   media_mounted
    if (environment.getexternalstoragestate().equals(environment.media_mounted)) {
      return true;
    } else {
      return false;
    }
  }

  /*
   * 剪切图片
   */
  private void crop(uri uri) {
    // 裁剪图片意图
    intent intent = new intent("com.android.camera.action.crop");
    intent.setdataandtype(uri, "image/*");
    intent.putextra("crop", "true");
    // 裁剪框的比例,1:1
    intent.putextra("aspectx", 1);
    intent.putextra("aspecty", 1);
    // 裁剪后输出图片的尺寸大小
    intent.putextra("outputx", 250);
    intent.putextra("outputy", 250);

    intent.putextra("outputformat", "jpeg");// 图片格式
    intent.putextra("nofacedetection", true);// 取消人脸识别
    intent.putextra("return-data", true);
    // 开启一个带有返回值的activity,请求码为photo_request_cut
    startactivityforresult(intent, photo_request_cut);
  }

  /**
   *
   * @param requestcode
   * @param resultcode
   * @param data
   */
  @override
  protected void onactivityresult(int requestcode, int resultcode, intent data) {
    if (requestcode == photo_request_gallery) {
      // 从相册返回的数据
      if (data != null) {
        // 得到图片的全路径
        uri uri = data.getdata();
        crop(uri);
      }
    } else if (requestcode == photo_request_carema) {
      // 从相机返回的数据
      if (hassdcard()) {
        crop(uri.fromfile(tempfile));
      } else {
        toast.maketext(mainactivity.this, "未找到存储卡,无法存储照片!", toast.length_short).show();
      }
    } else if (requestcode == photo_request_cut) {
      // 从剪切图片返回的数据
      if (data != null) {
        bitmap bitmap = data.getparcelableextra("data");
        /**
         * 获得图片
         */
        iv_img.setimagebitmap(bitmap);
        //保存到sharedpreferences
        savebitmaptosharedpreferences(bitmap);
      }
      try {
        // 将临时文件删除
        tempfile.delete();
      } catch (exception e) {
        e.printstacktrace();
      }
    }
    super.onactivityresult(requestcode, resultcode, data);
  }

  //保存图片到sharedpreferences
  private void savebitmaptosharedpreferences(bitmap bitmap) {
    // bitmap bitmap=bitmapfactory.decoderesource(getresources(), r.drawable.ic_launcher);
    //第一步:将bitmap压缩至字节数组输出流bytearrayoutputstream
    bytearrayoutputstream bytearrayoutputstream = new bytearrayoutputstream();
    bitmap.compress(bitmap.compressformat.png, 80, bytearrayoutputstream);
    //第二步:利用base64将字节数组输出流中的数据转换成字符串string
    byte[] bytearray = bytearrayoutputstream.tobytearray();
    string imagestring = new string(base64.encodetostring(bytearray, base64.default));
    //第三步:将string保持至sharedpreferences
    sharedpreferences sharedpreferences = getsharedpreferences("testsp", context.mode_private);
    sharedpreferences.editor editor = sharedpreferences.edit();
    editor.putstring("image", imagestring);
    editor.commit();

    //上传头像
    setimgbystr(imagestring,"");
  }


  /**
   * 上传头像
   * @param imgstr
   * @param imgname
   */
  public void setimgbystr(string imgstr, string imgname) {
  //这里是头像接口,通过post请求,拼接接口地址和id,上传数据。
    string url = "http://这里写的是接口地址(具体接收格式要看后台怎么给)";
    map<string, string> params = new hashmap<string, string>();
    params.put("id", "11111111");// 11111111
    params.put("data", imgstr);
    okhttp.postasync(url, params, new okhttp.datacallback() {
      @override
      public void requestfailure(request request, ioexception e) {
        log.i("上传失败", "失败" + request.tostring() + e.tostring());
      }
      @override
      public void requestsuccess(string result) throws exception {
        toast.maketext(mainactivity.this,"上传成功",toast.length_short).show();
        log.i("上传成功", result);
      }
    });
  }

  //从sharedpreferences获取图片
  private void getbitmapfromsharedpreferences(){
    sharedpreferences sharedpreferences=getsharedpreferences("testsp", context.mode_private);
    //第一步:取出字符串形式的bitmap
    string imagestring=sharedpreferences.getstring("image", "");
    //第二步:利用base64将字符串转换为bytearrayinputstream
    byte[] bytearray= base64.decode(imagestring, base64.default);
    if(bytearray.length==0){
      iv_img.setimageresource(r.mipmap.ic_launcher);
    }else{
      bytearrayinputstream bytearrayinputstream=new bytearrayinputstream(bytearray);

      //第三步:利用bytearrayinputstream生成bitmap
      bitmap bitmap= bitmapfactory.decodestream(bytearrayinputstream);
      iv_img.setimagebitmap(bitmap);
    }

  }

}


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网