我刚接触android,只是制作了一个虚拟应用程序,其中有一个对话框,其中提供了单击图像或从图库中选择图像的选项。 一切工作都很好,我从相机捕获图像,然后将其保存在应用程序的本地文件夹中,就像从图库中选取图像时一样,将其复制并保存在自己的文件夹中。 但是我需要添加1个功能,无论何时从相机或画廊中选择图像,我都应该获得裁剪选项,以便在完成裁剪后应该保存该图像,但我尝试了很多,但是未能提供我的代码,请看一下,如果可能的话,请简单回答。 预先感谢...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
mDob = findViewById(R.id.dob);
mGender = findViewById(R.id.ep_gender);
Button cancel = findViewById(R.id.ep_cancel);
Button done = findViewById(R.id.ep_done);
userName = findViewById(R.id.ep_username);
TextView cPassword = findViewById(R.id.ep_password);
backgroundPic = findViewById(R.id.iv_blur_background);
mainProfilePic = findViewById(R.id.ep_profile_image);
ImageView uploadPic = findViewById(R.id.iv_upload_pic);
homeLayout = findViewById(R.id.homelayout);
//for camera image pic
// Checking availability of the camera
if (!CameraUtils.isDeviceSupportCamera(getApplicationContext())) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device doesn't have camera
finish();
}
//Initializing Shared Preference
mySharedPreference = MySharedPreference.getInstance(this);
//Initializing myDao
AppDatabase appDatabase;
appDatabase=AppDatabase.getInstance(this);
myDao=appDatabase.myDao();
fetchId();
new MyAsyncSetData().execute();
mGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId==R.id.ep_female){
gender=FEMALE;
}else{
if(checkedId==R.id.ep_male){
gender=MALE;
}
}
}
});
mDob.setOnClickListener(this);
cancel.setOnClickListener(this);
done.setOnClickListener(this);
cPassword.setOnClickListener(this);
uploadPic.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.dob:
SelectDate();
break;
case R.id.ep_cancel:
finish();
break;
case R.id.ep_password:
Intent i = new Intent(this,ChangePassword.class);
startActivity(i);
break;
case R.id.ep_done:
new MyAsyncUpdateData().execute();
break;
case R.id.iv_upload_pic:
// to make background bit dully
homeLayout.setAlpha(0.5f);
dialog=new Dialog(this);
Button btnGallery,btnCamera,btnRemove;
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // used to remove the title of dialog
dialog.setContentView(R.layout.customdialoglayout);
btnGallery=dialog.findViewById(R.id.btnGalleryPicture);
btnCamera=dialog.findViewById(R.id.btnCapturePicture);
btnRemove=dialog.findViewById(R.id.btnRemove);
//dialog does not close on clicking outside
btnGallery.setOnClickListener(this);
btnCamera.setOnClickListener(this);
btnRemove.setOnClickListener(this);
dialog.show();// shows the dialog
dialog.getWindow().setAttributes(lp);
// to cancel the blurry effect on background layout
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
homeLayout.setAlpha(1.0f);
}
});
break;
case R.id.btnGalleryPicture:
Intent pickPhoto = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , REQUEST_TAKE_PHOTO_GALLERY);//one can be replaced with any action code
dialog.dismiss();//closes the custom dialog
break;
case R.id.btnCapturePicture:
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.vshop.vshop",
photoFile);
Log.d("camera uri", photoURI.toString());
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO_CAMERA);
}
}
dialog.dismiss();//closes the custom dialog
break;
case R.id.btnRemove:
mCurrentPhotoPath=DEFAULT_PICTURE;
loadDefaultImages();
break;
}
}
//loading last updated pictures to edit profile
private void loadDefaultImages()
{
mainProfilePic.setImageDrawable(getResources().getDrawable(R.drawable.user));
backgroundPic.setImageDrawable(getResources().getDrawable(R.drawable.blur));
dialog.dismiss();
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case REQUEST_TAKE_PHOTO_CAMERA:
if (resultCode == RESULT_OK) {
LoadImages();
} else { // Result was a failure
Toast.makeText(this, ERROR_CAPTURING, Toast.LENGTH_SHORT).show();
}
break;
case REQUEST_TAKE_PHOTO_GALLERY:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
File file=null;
try {
file=createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if(file!=null)
{
boolean isCopied=copyUriToFile(this,file,selectedImage);
if(isCopied)
{
LoadImages();
}
}
}
break;
}
}
private void LoadImages(){
//using Universal Image Loader Library for loading and displaying image
ImageLoader.getInstance()
.displayImage(mCurrentPhotoPath//string url
,mainProfilePic);//imageview for showing image
Uri myUri = Uri.parse(mCurrentPhotoPath);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), myUri);
} catch (IOException e) {
e.printStackTrace();
}
BlurImage.with(getApplicationContext()).load(bitmap).intensity(10).Async(true).into(backgroundPic);
/* ImageLoader.getInstance()
.displayImage(mCurrentPhotoPath//string url
,backgroundPic);*/
}
public class MyAsyncSetData extends AsyncTask<Void,Void,User>{
@Override
protected User doInBackground(Void... voids) {
User user = SetOldResult(user_id);
return user;
}
//Initializing Query to get details of current user
private User SetOldResult(long id){
User user;
user = myDao.getUserDetails(id);
return user;
}
@Override
protected void onPostExecute(User user) {
String gender = user.getGender();
String dob = user.getDob();
String fName = user.getFname();
String lName = user.getLname();
String Name = fName + " " + lName;
String picUri =user.getImageUri();
userName.setText(Name);
mDob.setText(dob);
if(gender.equals("male")){
mGender.check(R.id.ep_male);
}
else if(gender.equals("female")){
mGender.check(R.id.ep_female);
}
if (picUri.equals(DEFAULT_PICTURE)){
backgroundPic.setImageDrawable(getResources().getDrawable(R.drawable.blur));
mainProfilePic.setImageDrawable(getResources().getDrawable(R.drawable.user));
}else {
mCurrentPhotoPath=picUri;
LoadImages();
}
}
}
public class MyAsyncUpdateData extends AsyncTask<Void,Void,Integer>{
@Override
protected void onPreExecute() {
mProgressDialog=new ProgressDialog(EditProfile.this);
mProgressDialog.setTitle("Updating");
mProgressDialog.setMessage("Your current changes are being updated please wait..");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
@Override
protected Integer doInBackground(Void... voids) {
//just to show dialog box to delay our action by 3 seconds
try{
Thread.sleep(1500);
}
catch(Exception e)
{
e.printStackTrace();
}
int i = myDao.updateGenderAndDob(mCurrentPhotoPath,gender,mDob.getText().toString(),user_id);
return i;
}
@Override
protected void onPostExecute(Integer integer) {
mProgressDialog.dismiss();
if(integer>0){
mySharedPreference.savePathProfileImage(mCurrentPhotoPath);
finish();
}else {
Toast.makeText(EditProfile.this,ERROR_UPDATING,Toast.LENGTH_SHORT).show();
}
}
}
//Getting Id of current logged in user
private void fetchId(){
user_id = mySharedPreference.fetchId();
}
// method to pick and set dob
private void SelectDate(){
Calendar calendar=Calendar.getInstance();//to get current time and date
int currentYear= calendar.get(Calendar.YEAR);
int currentMonth=calendar.get(Calendar.MONTH);
int currentDay=calendar.get(Calendar.DATE);
DatePickerDialog datePickerDialog=new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
mDob.setText(dayOfMonth+"."+(month+1)+"."+year);
}
},currentYear,currentMonth,currentDay);
datePickerDialog.getDatePicker().setMaxDate(calendar.getTimeInMillis());
datePickerDialog.setCancelable(false);
datePickerDialog.show();
}
//used to create new file in our own app folder
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
mCurrentPhotoPath = "file://"+image.getAbsolutePath();
Log.d("camera", mCurrentPhotoPath);
return image;
}
//This is used to copy image_file from gallery to local app folder
public boolean copyUriToFile(Context c, File file, Uri uri) {
try {
InputStream is = c.getContentResolver().openInputStream(uri);
FileOutputStream fos = new FileOutputStream(file);
copyStream(is, fos);
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public void copyStream(InputStream input, OutputStream output)
throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
}