Я создал функцию камеры для отображения в ImageView. Кроме того, я создал кнопку для сохранения изображения во внутреннем хранилище и создал путь к ним к файлу.
Я не уверен, как отобразить изображение в ImageView. Мне нужна помощь со строкой кода, выделенной жирным шрифтом . Заранее большое спасибо.
public class TakeAndViewPhoto extends AppCompatActivity {
private static int REQUEST_CODE_PERMISSIONS = 1;
private static int REQUEST_CODE_CAPTURE_IMAGE = 2;
private String currentImagePath;
private ImageView imageView;
private ImageButton imageButton;
OutputStream outputStream;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson);
imageView = findViewById(R.id.captured_image);
imageButton = findViewById(R.id.button_save_image);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath() + "/lesson/");
dir.mkdir();
File file = new File(dir, System.currentTimeMillis()+".jpg");
try {
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
Toast.makeText(getApplicationContext(),"Image save to internal!",Toast.LENGTH_LONG).show();
try {
outputStream.flush();
} catch (IOException e){
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
findViewById(R.id.button_capture_image).setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(
getApplicationContext(),
Manifest.permission.CAMERA
) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(
getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
TakeAndViewPhoto.this,
new String[]{
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
REQUEST_CODE_PERMISSIONS
);
} else {
sendCaptureImageIntent();
}
}
});
}
private void sendCaptureImageIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
File imageFile = null;
try {
imageFile = createImageFile();
} catch (IOException exception) {
Toast.makeText(this, exception.getMessage(), Toast.LENGTH_SHORT).show();
}
if (imageFile != null) { Uri imageUri = FileProvider.getUriForFile(this, "com.appname.fileprovider",imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_CODE_CAPTURE_IMAGE);
}
}
}
private File createImageFile() throws IOException {
String fileName = "Image_" + new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.getDefault()).format(new Date());
File directory = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(fileName,".jpg",directory);
currentImagePath = imageFile.getAbsolutePath();
return imageFile;
}
@Override
public void onRequestPermissionsResult (int requiresCode, @NonNull String[] permissions, @NonNull int [] grantResults) {
super.onRequestPermissionsResult(requiresCode, permissions, grantResults);
if (requiresCode == REQUEST_CODE_PERMISSIONS && grantResults.length >0 ){
if (grantResults [0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
sendCaptureImageIntent();
} else {
Toast.makeText(this, "Not all permissions granted" ,Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == REQUEST_CODE_CAPTURE_IMAGE && resultCode == RESULT_OK) {
try{
//Display scaled smaller image
imageView.setImageBitmap(getScaledBitmap(imageView));
**File capturedImageFile = new File(currentImagePath);** // <-- this line
Toast.makeText(this, "Upload success", Toast.LENGTH_SHORT).show();
} catch (Exception exception) {
Toast.makeText(this, exception.getMessage(), Toast.LENGTH_SHORT).show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private Bitmap getScaledBitmap (ImageView imageView) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
int scaleFactor = Math.min(
options.outWidth / imageView.getWidth(),
options.outHeight / imageView.getHeight()
);
options.inJustDecodeBounds = false;
options.inSampleSize = scaleFactor;
options.inPurgeable = true;
return BitmapFactory.decodeFile(currentImagePath,options);
}
}