Я пытаюсь загрузить изображение из приложения для Android на сервер. Я вызываю функцию загрузки и пытаюсь получить изображение из ImageVeiw, но безуспешно. Изображение устанавливается на ImageVeiw из галереи или камеры. Невозможно получить файл для отправки на сервер
Это мой код, который я использую для установки изображения с камеры и галереи.
if(requestCode == CAMERA_REQUEST & resultCode == RESULT_OK){
Log.d("camera/gallery", "camera");
Bitmap photo = (Bitmap) data.getExtras().get("data");
profilePicture.setImageBitmap(photo);
} else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Log.d("camera/gallery", "gallery");
// get image from gallery
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap loadedBitmap = BitmapFactory.decodeFile(picturePath);
// check orientation of image and rotate if required
ExifInterface exifInterface = null;
try{
File pictureFile = new File(picturePath);
exifInterface = new ExifInterface(pictureFile.getAbsolutePath());
} catch (IOException e){
e.printStackTrace();
}
int orientation = exifInterface.ORIENTATION_NORMAL;
if(exifInterface != null){
orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
}
switch(orientation){
case ExifInterface.ORIENTATION_ROTATE_90:
loadedBitmap = rotateBitmap(loadedBitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
loadedBitmap = rotateBitmap(loadedBitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
loadedBitmap = rotateBitmap(loadedBitmap, 270);
break;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
loadedBitmap = flipBitmap(loadedBitmap, true, false);
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
loadedBitmap = flipBitmap(loadedBitmap, false, true);
default:
loadedBitmap = loadedBitmap;
}
// set image to ImageView
profilePicture.setImageBitmap(loadedBitmap);
}
Я могу получить растровое изображение ипытаясь сохранить его в файл. Позже я пытаюсь извлечь тот же файл и загрузить его на сервер, используя модификацию
. Я получаю эту ошибку от модификации после сбоя
W/System.err: java.io.FileNotFoundException: file:/data/user/0/com.example.fileuploaddemo/files/cleaton_profile_20191023T111341.png (No such file or directory)
Код для хранения и получения файла и отправкифайл изображения
public void uploadProfileImage(){
Uri fileUri = getSelectedFile();
if(Uri.EMPTY.equals(fileUri)){
Toast.makeText(this, "Exception Occurred", Toast.LENGTH_SHORT).show();
} else {
File originalFile = FileUtils.getFile(fileUri.toString());
Log.d(TAG, "in upload"+originalFile.getAbsolutePath());
RequestBody filePart = RequestBody.create(MediaType.parse("image/*"), originalFile);
MultipartBody.Part file = MultipartBody.Part.createFormData("upload", originalFile.getName(), filePart);
RequestBody modePart = RequestBody.create(MultipartBody.FORM, "profilepicture");
APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
apiInterface.uploadPhoto(file, modePart).enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Toast.makeText(MainActivity.this, "File Uploaded", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "Upload Fail", Toast.LENGTH_SHORT).show();
t.printStackTrace();
}
});
}
}
public Uri getSelectedFile(){
try{
String username = "cleaton";
// get bitmap from image set on imageview and convert to byte array
BitmapDrawable bitmapDrawable = (BitmapDrawable) profilePicture.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
byte[] bitmapdata = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
String timeStamp = dateFormat.format(new Date());
File file = new File(getFilesDir(), username+"_profile_"+timeStamp+".png");
// insert byte array into file output stream with name
FileOutputStream fileOutputStream = openFileOutput(username+"_profile_"+timeStamp+".png", MODE_PRIVATE);
fileOutputStream.write(bitmapdata);
fileOutputStream.flush();
fileOutputStream.close();
File profileImageFile = new File(file.getAbsolutePath());
Log.d(TAG, "file retrieve"+profileImageFile);
Uri fileUri = Uri.fromFile(profileImageFile);
Log.d(TAG, "file Uri"+fileUri);
return fileUri;
} catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
return null;
}
catch(IOException ioe){
ioe.printStackTrace();
return null;
}
}