欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android实现调用系统图库与相机设置头像并保存在本地及服务器

程序员文章站 2023-12-05 21:01:34
废话不多说了,直接给大家贴代码了,具体代码如下所述: /** * 1、实现原理:用户打开相册或相机选择相片后,相片经过压缩并设置在控件上,图片在本地sd卡存一...

废话不多说了,直接给大家贴代码了,具体代码如下所述:

/**
 * 1、实现原理:用户打开相册或相机选择相片后,相片经过压缩并设置在控件上,图片在本地sd卡存一份(如果有的话,没有则内部存储,所以还
 * 需要判断用户是否挂载了sd卡),然后在服务器上存储一份该图片,当下次再次启动应用时,会默认去sd卡加载该图片,如果本地没有,再会去联网请求
 * 2、使用了picasso框架以及自定义bitmaputils工具类
 * 3、记得加上相关权限
 * <uses-permission android:name="android.permission.internet"></uses-permission>
 <uses-permission android:name="android.permission.camera"/>
 <uses-permission android:name="android.permission.write_external_storage"></uses-permission>
 * */
public class mainactivity extends appcompatactivity implements view.onclicklistener {
  private imageview iv;//要设置的头像
  private button btn_photo;//调用相册按钮
  private button btn_camera;//调用相机按钮
  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    iv=(imageview) findviewbyid(r.id.iv);
    btn_photo = (button) findviewbyid(r.id.btn_photo);
    btn_camera = (button) findviewbyid(r.id.btn_camera);
    btn_photo.setonclicklistener(this);
    btn_camera.setonclicklistener(this);
  }
  @override
  public void onclick(view v) {
    switch (v.getid()) {
      case r.id.btn_photo://打开系统相册
        intent intent=new intent(intent.action_pick, mediastore.images.media.external_content_uri);
        startactivityforresult(intent,100);
        break;
      case r.id.btn_camera://打开系统相机
        intent intent2=new intent(mediastore.action_image_capture);
        startactivityforresult(intent2,200);
        break;
    }
  }
  @requiresapi(api = build.version_codes.kitkat)
  @override
  protected void onactivityresult(int requestcode, int resultcode, intent data) {
    super.onactivityresult(requestcode, resultcode, data);
    if(requestcode==100&&resultcode==result_ok&&data!=null){//系统相册
      uri imagedata = data.getdata();
      string path=getpath(imagedata);
      bitmap bitmap = bitmapfactory.decodefile(path);
      bitmap bitmap1 = bitmaputils.zoom(bitmap, iv.getwidth(), iv.getheight());
      bitmap bitmap2 = bitmaputils.circlebitmap(bitmap1);
      //加载显示
      iv.setimagebitmap(bitmap2);
      //bitmap图片上传到服务器......
      //bitmap图片保存到本地
      saveimage(bitmap2);
    }else if(requestcode==200&&resultcode==result_ok&&data!=null){//系统相机
      bitmap bitmap = (bitmap) data.getextras().get("data");
      bitmaputils.zoom(bitmap,iv.getwidth(),iv.getheight());
      bitmap=bitmaputils.circlebitmap(bitmap);
      //加载显示
      iv.setimagebitmap(bitmap);
      //bitmap图片上传到服务器......
      //bitmap图片保存到本地
      saveimage(bitmap);
    }
  }
  /**
   * 数据的存储。(5种)
   * bimap:内存层面的图片对象。
   *
   * 存储--->内存:
   *   bitmapfactory.decodefile(string filepath);
   *   bitmapfactory.decodestream(inputstream is);
   * 内存--->存储:
   *   bitmap.compress(bitmap.compressformat.png,100,outputstream os);
   */
  private void saveimage(bitmap bitmap) {
    file filesdir;
    if(environment.getexternalstoragestate().equals(environment.media_mounted)){//判断sd卡是否挂载
      //路径1:storage/sdcard/android/data/包名/files
      filesdir = this.getexternalfilesdir("");
    }else{//手机内部存储
      //路径:data/data/包名/files
      filesdir = this.getfilesdir();
    }
    fileoutputstream fos = null;
    try {
      file file = new file(filesdir,"icon.png");
      fos = new fileoutputstream(file);
      bitmap.compress(bitmap.compressformat.png, 100,fos);
    } catch (filenotfoundexception e) {
      e.printstacktrace();
    }finally{
      if(fos != null){
        try {
          fos.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
    }
  }
  //如果本地有,就不需要再去联网去请求
  private boolean readimage() {
    file filesdir;
    if(environment.getexternalstoragestate().equals(environment.media_mounted)){//判断sd卡是否挂载
      //路径1:storage/sdcard/android/data/包名/files
      filesdir = getexternalfilesdir("");
    }else{//手机内部存储
      //路径:data/data/包名/files
      filesdir = getfilesdir();
    }
    file file = new file(filesdir,"icon.png");
    if(file.exists()){
      //存储--->内存
      bitmap bitmap = bitmapfactory.decodefile(file.getabsolutepath());
      iv.setimagebitmap(bitmap);
      return true;
    }
    return false;
  }
  @requiresapi(api = build.version_codes.kitkat)
  private string getpath(uri uri) {
    int sdkversion = build.version.sdk_int;
    //高于4.4.2的版本
    if (sdkversion >= 19) {
      log.e("tag", "uri auth: " + uri.getauthority());
      if (isexternalstoragedocument(uri)) {
        string docid = documentscontract.getdocumentid(uri);
        string[] split = docid.split(":");
        string type = split[0];
        if ("primary".equalsignorecase(type)) {
          return environment.getexternalstoragedirectory() + "/" + split[1];
        }
      } else if (isdownloadsdocument(uri)) {
        final string id = documentscontract.getdocumentid(uri);
        final uri contenturi = contenturis.withappendedid(uri.parse("content://downloads/public_downloads"),
            long.valueof(id));
        return getdatacolumn(this, contenturi, null, null);
      } else if (ismediadocument(uri)) {
        final string docid = documentscontract.getdocumentid(uri);
        final string[] split = docid.split(":");
        final string type = split[0];
        uri contenturi = null;
        if ("image".equals(type)) {
          contenturi = mediastore.images.media.external_content_uri;
        } else if ("video".equals(type)) {
          contenturi = mediastore.video.media.external_content_uri;
        } else if ("audio".equals(type)) {
          contenturi = mediastore.audio.media.external_content_uri;
        }
        final string selection = "_id=?";
        final string[] selectionargs = new string[]{split[1]};
        return getdatacolumn(this, contenturi, selection, selectionargs);
      } else if (ismedia(uri)) {
        string[] proj = {mediastore.images.media.data};
        cursor actualimagecursor = this.managedquery(uri, proj, null, null, null);
        int actual_image_column_index = actualimagecursor.getcolumnindexorthrow(mediastore.images.media.data);
        actualimagecursor.movetofirst();
        return actualimagecursor.getstring(actual_image_column_index);
      }
    } else if ("content".equalsignorecase(uri.getscheme())) {
      // return the remote address
      if (isgooglephotosuri(uri))
        return uri.getlastpathsegment();
      return getdatacolumn(this, uri, null, null);
    }
    // file
    else if ("file".equalsignorecase(uri.getscheme())) {
      return uri.getpath();
    }
    return null;
  }
  /**
   * uri路径查询字段
   *
   * @param context
   * @param uri
   * @param selection
   * @param selectionargs
   * @return
   */
  public static string getdatacolumn(context context, uri uri, string selection, string[] selectionargs) {
    cursor cursor = null;
    final string column = "_data";
    final string[] projection = {column};
    try {
      cursor = context.getcontentresolver().query(uri, projection, selection, selectionargs, null);
      if (cursor != null && cursor.movetofirst()) {
        final int index = cursor.getcolumnindexorthrow(column);
        return cursor.getstring(index);
      }
    } finally {
      if (cursor != null)
        cursor.close();
    }
    return null;
  }
  private boolean isexternalstoragedocument(uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getauthority());
  }
  public static boolean isdownloadsdocument(uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getauthority());
  }
  public static boolean ismediadocument(uri uri) {
    return "com.android.providers.media.documents".equals(uri.getauthority());
  }
  public static boolean ismedia(uri uri) {
    return "media".equals(uri.getauthority());
  }
  /**
   * @param uri the uri to check.
   * @return whether the uri authority is google photos.
   */
  public static boolean isgooglephotosuri(uri uri) {
    return "com.google.android.apps.photos.content".equals(uri.getauthority());
  }
  /**
   * 判断本地是否有该图片,没有则去联网请求
   * */
  @override
  protected void onresume() {
    super.onresume();
    if(readimage()){
      return;
    }
  }
}
//bitmaputils工具类public class bitmaputils { /**
   * 该方法用于将图片进行圆形处理
   * */  public static bitmap circlebitmap(bitmap source){    //默认只对宽进行处理    int width=source.getwidth();    bitmap bitmap=bitmap.createbitmap(width,width,bitmap.config.argb_8888);    canvas canvas=new canvas(bitmap);    paint paint=new paint();    //设置抗锯齿    paint.setantialias(true);    canvas.drawcircle(width/2,width/2,width/2,paint);    paint.setxfermode(new porterduffxfermode(porterduff.mode.src_in));    canvas.drawbitmap(source,0,0,paint);    return bitmap;  }  /**   * 该方法用于图片压缩处理,注意width、height参数的类型必须是float   * */  public static bitmap zoom(bitmap source,float width,float height){    matrix matrix=new matrix();    //图片进行压缩处理    matrix.postscale(width/source.getwidth(),height/source.getheight());    bitmap bitmap = bitmap.createbitmap(source, 0, 0, source.getwidth(), source.getheight(), matrix, false);    return bitmap;  }}

以上所述是小编给大家介绍的android实现调用系统图库与相机设置头像并保存在本地及服务器 ,希望对大家有所帮助