我正在研究的Android app
上需要帮助。
该应用程序允许用户从gallery
或camera
中选择一张照片,然后裁剪图像,最后将图像上传到server
。
要裁剪图像,我使用了 yalantis 的uCrop库,并将照片上传到了我使用Retrofit
的服务器上。
我遇到的问题是我选择了image
,裁剪,然后当我将其保存在server
上时,保存了原始图片,而不保存裁剪的图像。
有人可以告诉我为什么会这样吗?
这是我的代码:
MainActivity
public class MainActivity extends AppCompatActivity implements IImagePickerLister{
Bitmap bitmap;
private ImageView imageView;
Button selectImg,uploadImg;
EditText imgTitle;
private static final int IMAGE = 100;
private ProgressBar progressBar;
private static final int CAMERA_ACTION_PICK_REQUEST_CODE = 610;
private static final int PICK_IMAGE_GALLERY_REQUEST_CODE = 600;
public static final int CAMERA_STORAGE_REQUEST_CODE = 611;
public static final int ONLY_CAMERA_REQUEST_CODE = 612;
public static final int ONLY_STORAGE_REQUEST_CODE = 613;
private String currentPhotoPath = "";
private UiHelper uiHelper = new UiHelper();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
selectImg = (Button) findViewById(R.id.button);
uploadImg = (Button) findViewById(R.id.button2);
imgTitle = (EditText) findViewById(R.id.editText);
progressBar = (ProgressBar) findViewById(R.id.progressBar_cyclic);
findViewById(R.id.button).setOnClickListener(v -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
if (uiHelper.checkSelfPermissions(this))
uiHelper.showImagePickerDialog(this, this);
});
uploadImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
validateImage();
}
});
}
private void validateImage() {
//find values
final String regName = imgTitle.getText().toString();
String image = convertToString();
// checking if username is empty
if (TextUtils.isEmpty(regName)) {
Toast.makeText(MainActivity.this, "Seleziona i metodi di pagamento del tuo locale.", Toast.LENGTH_LONG).show();
return;
}
//checking if email is empty
//checking if password is empty
//After Validating we register User
uploadImage(regName, image);
}
private String convertToString()
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.WEBP,75,byteArrayOutputStream);
byte[] imgByte = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imgByte,Base64.DEFAULT);
}
private void uploadImage(String imageNome, String image){
ApiInterface api = ApiClient.createService(ApiInterface.class);
Call<Img_Pojo> login = api.uploadImage(imageNome,image);
login.enqueue(new Callback<Img_Pojo>() {
@Override
public void onResponse(Call<Img_Pojo> call, Response<Img_Pojo> response) {
if(Objects.requireNonNull(response.body()).getIsSuccess() == 1) {
startActivity(new Intent(MainActivity.this,Main2Activity.class));
Toast.makeText(MainActivity.this, "Informazioni inserite!", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
else{
Toast.makeText(MainActivity.this,response.body().getMessage(),Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<Img_Pojo> call, Throwable t) {
Toast.makeText(MainActivity.this,t.getLocalizedMessage(),Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == CAMERA_STORAGE_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED)
uiHelper.showImagePickerDialog(this, this);
else if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_DENIED) {
uiHelper.toast(this, "ImageCropper needs Storage access in order to store your profile picture.");
finish();
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
uiHelper.toast(this, "ImageCropper needs Camera access in order to take profile picture.");
finish();
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED && grantResults[1] == PackageManager.PERMISSION_DENIED) {
uiHelper.toast(this, "ImageCropper needs Camera and Storage access in order to take profile picture.");
finish();
}
} else if (requestCode == ONLY_CAMERA_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
uiHelper.showImagePickerDialog(this, this);
else {
uiHelper.toast(this, "ImageCropper needs Camera access in order to take profile picture.");
finish();
}
} else if (requestCode == ONLY_STORAGE_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
uiHelper.showImagePickerDialog(this, this);
else {
uiHelper.toast(this, "ImageCropper needs Storage access in order to store your profile picture.");
finish();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_ACTION_PICK_REQUEST_CODE && resultCode == RESULT_OK) {
Uri uri = Uri.parse(currentPhotoPath);
openCropActivity(uri, uri);
} else if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
if (data != null) {
Uri uri = UCrop.getOutput(data);
showImage(uri);
}
} else if (requestCode == PICK_IMAGE_GALLERY_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
try {
Uri sourceUri = data.getData();
File file = getImageFile();
Uri destinationUri = Uri.fromFile(file);
openCropActivity(sourceUri, destinationUri);
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),sourceUri);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
uiHelper.toast(this, "Please select another image");
}
}
}
private void openImagesDocument() {
Intent pictureIntent = new Intent(Intent.ACTION_GET_CONTENT);
pictureIntent.setType("image/*");
pictureIntent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
String[] mimeTypes = new String[]{"image/jpeg", "image/png"};
pictureIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
}
startActivityForResult(Intent.createChooser(pictureIntent, "Select Picture"), PICK_IMAGE_GALLERY_REQUEST_CODE);
}
private void showImage(Uri imageUri) {
try {
File file;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
file = FileUtils.getFile(this, imageUri);
} else {
file = new File(currentPhotoPath);
}
InputStream inputStream = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
uiHelper.toast(this, "Please select different profile picture.");
}
}
private void openCamera() {
Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file;
try {
file = getImageFile(); // 1
} catch (Exception e) {
e.printStackTrace();
uiHelper.toast(this, "Please take another image");
return;
}
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) // 2
uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID.concat(".provider"), file);
else
uri = Uri.fromFile(file); // 3
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri); // 4
startActivityForResult(pictureIntent, CAMERA_ACTION_PICK_REQUEST_CODE);
}
private File getImageFile() throws IOException {
String imageFileName = "JPEG_" + System.currentTimeMillis() + "_";
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM
), "Camera"
);
System.out.println(storageDir.getAbsolutePath());
if (storageDir.exists())
System.out.println("File exists");
else
System.out.println("File not exists");
File file = File.createTempFile(
imageFileName, ".jpg", storageDir
);
currentPhotoPath = "file:" + file.getAbsolutePath();
return file;
}
private void openCropActivity(Uri sourceUri, Uri destinationUri) {
UCrop.Options options = new UCrop.Options();
options.setCropFrameColor(ContextCompat.getColor(this, R.color.colorAccent));
UCrop.of(sourceUri, destinationUri)
.withMaxResultSize(1080, 540)
.withAspectRatio(16, 9)
.start(this);
}
@Override
public void onOptionSelected(ImagePickerEnum imagePickerEnum) {
if (imagePickerEnum == ImagePickerEnum.FROM_CAMERA)
openCamera();
else if (imagePickerEnum == ImagePickerEnum.FROM_GALLERY)
openImagesDocument();
}
}