帶貨直播系統,實現簡單的換頭像並儲存

雲豹網路科技發表於2020-10-20

帶貨直播系統,實現簡單的換頭像並儲存的相關程式碼

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;

    }
}

以上就是 帶貨直播系統,實現簡單的換頭像並儲存的相關程式碼,更多內容歡迎關注之後的文章

相關文章