一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

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

时间:2022-06-25 23:27:27 编辑:袖梨 来源:一聚教程网

 

 代码如下复制代码

/**

 * 1、实现原理:用户打开相册或相机选择相片后,相片经过压缩并设置在控件上,图片在本地sd卡存一份(如果有的话,没有则内部存储,所以还

 * 需要判断用户是否挂载了sd卡),然后在服务器上存储一份该图片,当下次再次启动应用时,会默认去sd卡加载该图片,如果本地没有,再会去联网请求

 * 2、使用了picasso框架以及自定义BitmapUtils工具类

 * 3、记得加上相关权限

 *

 

 

 * */

publicclassMainActivityextendsAppCompatActivityimplementsView.OnClickListener {

  privateImageView iv;//要设置的头像

  privateButton btn_photo;//调用相册按钮

  privateButton btn_camera;//调用相机按钮

  @Override

  protectedvoidonCreate(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

  publicvoidonClick(View v) {

    switch(v.getId()) {

      caseR.id.btn_photo://打开系统相册

        Intent intent=newIntent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(intent,100);

        break;

      caseR.id.btn_camera://打开系统相机

        Intent intent2=newIntent(MediaStore.ACTION_IMAGE_CAPTURE);

        startActivityForResult(intent2,200);

        break;

    }

  }

  @RequiresApi(api = Build.VERSION_CODES.KITKAT)

  @Override

  protectedvoidonActivityResult(intrequestCode,intresultCode, 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);

    }elseif(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);

   */

  privatevoidsaveImage(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 =newFile(filesDir,"icon.png");

      fos =newFileOutputStream(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();

        }

      }

    }

  }

  //如果本地有,就不需要再去联网去请求

  privatebooleanreadImage() {

    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 =newFile(filesDir,"icon.png");

    if(file.exists()){

      //存储--->内存

      Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());

      iv.setImageBitmap(bitmap);

      returntrue;

    }

    returnfalse;

  }

  @RequiresApi(api = Build.VERSION_CODES.KITKAT)

  privateString getPath(Uri uri) {

    intsdkVersion = 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)) {

          returnEnvironment.getExternalStorageDirectory() +"/"+ split[1];

        }

      }elseif(isDownloadsDocument(uri)) {

        finalString id = DocumentsContract.getDocumentId(uri);

        finalUri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),

            Long.valueOf(id));

        returngetDataColumn(this, contentUri,null,null);

      }elseif(isMediaDocument(uri)) {

        finalString docId = DocumentsContract.getDocumentId(uri);

        finalString[] split = docId.split(":");

        finalString type = split[0];

        Uri contentUri =null;

        if("image".equals(type)) {

          contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

        }elseif("video".equals(type)) {

          contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;

        }elseif("audio".equals(type)) {

          contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

        }

        finalString selection ="_id=?";

        finalString[] selectionArgs =newString[]{split[1]};

        returngetDataColumn(this, contentUri, selection, selectionArgs);

      }elseif(isMedia(uri)) {

        String[] proj = {MediaStore.Images.Media.DATA};

        Cursor actualimagecursor =this.managedQuery(uri, proj,null,null,null);

        intactual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        actualimagecursor.moveToFirst();

        returnactualimagecursor.getString(actual_image_column_index);

      }

    }elseif("content".equalsIgnoreCase(uri.getScheme())) {

      // Return the remote address

      if(isGooglePhotosUri(uri))

        returnuri.getLastPathSegment();

      returngetDataColumn(this, uri,null,null);

    }

    // File

    elseif("file".equalsIgnoreCase(uri.getScheme())) {

      returnuri.getPath();

    }

    returnnull;

  }

  /**

   * uri路径查询字段

   *

   * @param context

   * @param uri

   * @param selection

   * @param selectionArgs

   * @return

   */

  publicstaticString getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

    Cursor cursor =null;

    finalString column ="_data";

    finalString[] projection = {column};

    try{

      cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,null);

      if(cursor !=null&& cursor.moveToFirst()) {

        finalintindex = cursor.getColumnIndexOrThrow(column);

        returncursor.getString(index);

      }

    }finally{

      if(cursor !=null)

        cursor.close();

    }

    returnnull;

  }

  privatebooleanisExternalStorageDocument(Uri uri) {

    return"com.android.externalstorage.documents".equals(uri.getAuthority());

  }

  publicstaticbooleanisDownloadsDocument(Uri uri) {

    return"com.android.providers.downloads.documents".equals(uri.getAuthority());

  }

  publicstaticbooleanisMediaDocument(Uri uri) {

    return"com.android.providers.media.documents".equals(uri.getAuthority());

  }

  publicstaticbooleanisMedia(Uri uri) {

    return"media".equals(uri.getAuthority());

  }

  /**

   * @param uri The Uri to check.

   * @return Whether the Uri authority is Google Photos.

   */

  publicstaticbooleanisGooglePhotosUri(Uri uri) {

    return"com.google.android.apps.photos.content".equals(uri.getAuthority());

  }

  /**

   * 判断本地是否有该图片,没有则去联网请求

   * */

  @Override

  protectedvoidonResume() {

    super.onResume();

    if(readImage()){

      return;

    }

  }

}

//BitmapUtils工具类public class BitmapUtils { /**

   * 该方法用于将图片进行圆形处理

   *  */ publicstaticBitmap 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;  }}

 

热门栏目