如何在相机和图库中设置图像

时间:2017-04-06 05:28:58

标签: java android imageview

我是一个新的Android。我想在图库中设置图像并从相机中捕获图像。当我点击更改照片按钮时,会出现一个对话框,图库或相机完全打开,但所选图像未在imageview.please帮助中设置。

public class Profile extends AppCompatActivity implements
View.OnClickListener{
private static final int SELECT_FILE = 1;
Button logOut;
Button GoHome;
Button Changepic;
ImageView IVProfile;
private Session session;
String userChoosenTask;
private static final int REQUEST_CAMERA = 1888;

void initViews(){

    logOut = (Button)findViewById(R.id.buttonLogout);
    GoHome = (Button)findViewById(R.id.buttonGoHome);
    Changepic = (Button)findViewById(R.id.buttonChangePic);
    session = new Session(this);
    logOut.setOnClickListener(this);
    GoHome.setOnClickListener(this);
    Changepic.setOnClickListener(this);

    if (!session.loggedin()){
        logout();
    }
}
private void logout() {
    session.SetLoggedin(false);
    finish();
    Intent i = new Intent(Profile.this, Login.class);
    startActivity(i);
}
private void selectImage() {
    final CharSequence[] items = { "Take Photo", "Choose from Library",
            "Cancel" };
    AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            boolean result=Utility.checkPermission(Profile.this);
            if (items[item].equals("Take Photo")) {
                userChoosenTask="Take Photo";
                if(result)
                    cameraIntent();
            } else if (items[item].equals("Choose from Library")) {
                userChoosenTask="Choose from Library";
                if(result)
                    galleryIntent();
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}


private void cameraIntent()
{
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent,REQUEST_CAMERA);
}

private void galleryIntent()
{
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select 
    File"),SELECT_FILE);

}

@Override
public void onRequestPermissionsResult(int requestCode, String[] 
     permissions, int[] grantResults) {
    switch (requestCode) {
        case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
            if (grantResults.length > 0 && grantResults[0] == 
          PackageManager.PERMISSION_GRANTED) {
                if(userChoosenTask.equals("Take Photo"))
                    cameraIntent();
                else if(userChoosenTask.equals("Choose from Library"))
                    galleryIntent();
            } else {
            }
            break;
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_FILE)
            onSelectFromGalleryResult(data);
        if (requestCode == REQUEST_CAMERA) {
            onCaptureImageResult(data);

        }
    }
}

private void onSelectFromGalleryResult(Intent data) {
    Bitmap bm=null;
    if (data != null) {
        try {
            bm = MediaStore.Images.Media.getBitmap(getApplicationContext()
   .getContentResolver(), data.getData());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    IVProfile.setImageBitmap(bm);
}

private void onCaptureImageResult(Intent data) {
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
    File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");
    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    IVProfile.setImageBitmap(thumbnail);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);
    String username = getIntent().getStringExtra("Username");
    TextView tvusername = (TextView)findViewById(R.id.textViewUsername);
    tvusername.setText(username);
    initViews();
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onClick(View v) {
    if( v.getId() == R.id.buttonLogout){
        logout();
    }
    else if (v.getId() == R.id.buttonGoHome){
        Intent i = new Intent(Profile.this,Home.class);
        startActivity(i);
    }
    else if (v.getId() == R.id.buttonChangePic){
        selectImage();
    }



  }
}

1 个答案:

答案 0 :(得分:1)

以下代码可用于拍摄和挑选照片以及选择照片或拍照。只需显示带有两个选项的对话框,并在选择时使用相应的代码。

  

从相机拍照:

Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);//zero can be replaced with any action code
  

从图库中选择照片:

Intent pickPhoto = new Intent(Intent.ACTION_PICK,
           android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);//one can be replaced with any action code
  

onActivityResult代码:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 
switch(requestCode) {
case 0:
    if(resultCode == RESULT_OK){  
        Bundle extras = imageReturnedIntent.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        imageview.setImageBitmap(imageBitmap);
    }
     break; 
case 1:
    if(resultCode == RESULT_OK){  
        Uri selectedImage = imageReturnedIntent.getData();
        imageview.setImageURI(selectedImage);
    }
    break;
  }
}
  

最后在清单文件中添加此权限:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />