仿抖音短视频APP源码,实现简单的换头像并保存

public class My_info extends AppCompatActivity implements View.OnClickListener {
private static final int CHOOSE_PHOTO=2;
private CircleImageView image;//一种用于图片圆形化的控件
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_info);
    image=(CircleImageView)findViewById(R.id.p_pic);
       if(readPac()!=null){        
              image.setImageBitmap(readPac());//如果头像修改过了,内存中已经新的头像图片。
        }
    @Override
    public void onClick(View v){
        switch (v.getId()){
             case R.id.alter:        //点击修改头像事件
             /
                if(ContextCompat.checkSelfPermission(My_info.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.
                PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(My_info.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                    //以上是访问图库的运行时权限/
                }else
                {
                    open();//打开图库
                }
                break;
            default: break;
        }
    }
    @Override
     //这里是对用户是否同意访问图库的处理
    public void onRequestPermissionsResult(int requestCode,String[] permissions,int [] grantResults){              
        switch (requestCode){
            case 1:
                if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    open();
                }else{
                    Toast.makeText(My_info.this,"您拒绝了权限",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }
    //打开图库
    private void open(){
        Intent intent=new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,CHOOSE_PHOTO);
    }

//
    @Override
    protected void onActivityResult(int requestCode,int reultCode,Intent data){
        switch (requestCode){
            case CHOOSE_PHOTO:
                if(reultCode==RESULT_OK){
                    handle(data);
                }
                break;
        }
    }
    private void handle(Intent data){
        String imagePath=null;
        Uri uri=data.getData();
        if(DocumentsContract.isDocumentUri(this,uri)){
            String docId=DocumentsContract.getDocumentId(uri);
       /     if("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id=docId.split(":")[1];
                String selection= MediaStore.Images.Media._ID+"="+id;
                imagePath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);

            }else if("com.android.providers.dowmloads.documents".equals(uri.getAuthority())){
                Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                imagePath=getImagePath(contentUri,null);

            }else if("content".equalsIgnoreCase(uri.getScheme())){
                imagePath=getImagePath(uri,null);
            }else if("file".equalsIgnoreCase(uri.getScheme())){
                imagePath=uri.getPath();
           }
            displayImage(imagePath);

        }

    }
    private String getImagePath(Uri uri,String selection){
        String path=null;
        Cursor cursor=getContentResolver().query(uri,null,selection,null,null);
        if(cursor!=null){
            if(cursor.moveToFirst()){
                path=cursor.getString(cursor.getColumnIndex(MediaStore.Ima//ges.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(Str/ing imagePath){
        if(imagePath!=null){
            Bitmap bitmap= BitmapFactory.decodeFile(imagePath);
            image.setImageBitmap(bitmap);
            Toast.makeText(My_info.this,"获取图片成功",Toast.LENGTH_SHORT).show();
            savePac(bitmap);

        }else {
            Toast.makeText(My_info.this,"获取图片失败",Toast.LENGTH_SHORT).show();
        }
    }

//以上获取图片的绝对路径再获取bitmap实例过程来自《第一行代码 第2版》P299//
//
//
//
    private void savePac(Bitmap bitmap){//保存图片
        String TargetPath=My_info.this.getFilesDir().toString()+File.separator+"imagic";//getFilesDir()方法用于获取/data/data//files目录
      File file=new File(TargetPath,"pac.jpg");
      file.delete();
      if(!file.exists()){
          file.getParentFile().mkdirs();
      }
      try{
          FileOutputStream fileOutputStrea=new FileOutputStream(file);
          bitmap.compress(Bitmap.CompressFormat.JPEG,80,fileOutputStream);
          fileOutputStream.flush();
          fileOutputStream.close();
      }catch (Exception e){
          Log.d("cnm", e.toString());
      }
    }
    private Bitmap readPac(){//读取图片
       String  savePath=My_info.this.getFilesDir().toString()+File.separator+"imagic"+File.separator+"pac.jpg";
        Bitmap bitmap = null;
        try{
                bitmap = BitmapFactory.decodeFile(savePath);
        } catch (Exception e) {}
        return bitmap;

    }
}
上一篇:Win7笔记本电脑启用虚拟WIFI共享上网


下一篇:Java中session的过时时间配置,session过时的优先级