ОБНОВЛЕНО с большим количеством кодаAndroid набор изображений из URI на ImageView
Я пытаюсь захватить изображение, которое было только что отснятый и установить его в ImageView
программно.
Кнопка фотография нажата,
picture_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
takePhoto(mTextureView);
}
});
он запускает метод takePhoto:
public void takePhoto(View view) {
try {
mImageFile = createImageFile();
final ImageView latest_picture = (ImageView) findViewById(R.id.latest_picture);
final RelativeLayout latest_picture_container = (RelativeLayout) findViewById(R.id.latest_picture_container);
final String mImageFileLocationNew = mImageFileLocation.replaceFirst("^/", "");
Toast.makeText(getApplicationContext(), "" + mImageFile, Toast.LENGTH_SHORT).show();
Uri uri = Uri.fromFile(mImageFile);
Toast.makeText(getApplicationContext(), ""+uri, Toast.LENGTH_LONG).show();
latest_picture.setImageURI(uri);
latest_picture_container.setVisibility(View.VISIBLE);
} catch (IOException e){
e.printStackTrace();
}
lockFocus();
captureStillImage();
}
, который работает createImageFile()
и captureStillImage()
private void captureStillImage() {
try {
CaptureRequest.Builder captureStillBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureStillBuilder.addTarget(mImageReader.getSurface());
int rotation = getWindowManager().getDefaultDisplay().getRotation();
captureStillBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
CameraCaptureSession.CaptureCallback captureCallback = new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
//Toast.makeText(getApplicationContext(), "Image Taken", Toast.LENGTH_SHORT).show();
unLockFocus();
}
};
mCameraCaptureSession.capture(captureStillBuilder.build(), captureCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
File createImageFile() throws IOException {
String timestamp = new SimpleDateFormat("yyyyMMdd").format(new Date());
String subFolder = "";
if(pref_session_unique_gallery.equals("yes")){
if(event_name != null){
subFolder = event_name;
} else {
subFolder = timestamp;
}
} else {
subFolder = "_GEN";
}
if(event_name == null){
event_name = "";
} else {
event_name = event_name + "_";
}
String imageFileName = "CPB_"+event_name+timestamp+"_";
File storageDirectory = new File(Environment.getExternalStorageDirectory() + File.separator + "CPB" + File.separator + subFolder);
storageDirectory.mkdir();
File image = File.createTempFile(imageFileName, ".jpg", storageDirectory);
mImageFileLocation = image.getAbsolutePath();
return image;
}
и изображение сохраняется здесь:
private static class ImageSaver implements Runnable {
private final Image mImage;
private ImageSaver(Image image) {
mImage = image;
}
@Override
public void run() {
ByteBuffer byteBuffer = mImage.getPlanes()[0].getBuffer();
byte[] bytes = new byte[byteBuffer.remaining()];
byteBuffer.get(bytes);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(mImageFile);
fileOutputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
mImage.close();
if(fileOutputStream != null){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Я получаю правильный путь к изображению после createImageFile()
и поджариваю его, чтобы показать, что это каждый раз. Но даже не setVisibility
на latest_picture_container
работает ... Если я прокомментирую InputStream
, Bitmap
и setImageBitmap
, тогда latest_picture_container
появится как обычно. Не уверен, почему это неправильно.
По какой-то причине, URI возвращается с тремя косыми чертами после файла,
file:///storage/0/...
Вы уверены, что вы получаете правильный путь к изображению? Вы пробовали распечатать путь? –
@ 4k3R Я только что узнал, что путь помещается в дополнительный файл '/' after': // ', поэтому я пытаюсь выяснить, откуда это происходит и как избавиться от него. – ntgCleaner
@ 4k3R, я добавлен метод создания изображения, если это поможет. – ntgCleaner