Android在ImageView上为URI设置图片

时间:2016-01-16 04:34:50

标签: android

更新了更多代码

我正在尝试抓取刚拍摄的照片并以编程方式将其设置为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工作正常......如果我评论InputStreamBitmapsetImageBitmap,那么latest_picture_container显示正常。不知道为什么这是错误的。

由于某种原因,URI在文件后面带有三个斜杠,

file:///storage/0/...

4 个答案:

答案 0 :(得分:3)

AssetManager#open()方法仅适用于您应用的资源;即项目的/assets文件夹中的文件。由于您尝试打​​开外部文件,因此应该在从路径创建的FileInputStream对象上使用File。此外,takePhoto()方法是在将任何内容写入文件之前在ImageView上设置图像,这将导致空ImageView

由于您的应用程序直接使用相机,我们可以从写入图像文件的相同字节数组中解码图像,并为自己节省不必要的存储读取。此外,在您的代码示例中,文件写入发生在单独的线程上,因此我们也可以在执行图像解码时利用它,因为它将最小化对UI线程的影响。

首先,我们将创建一个界面,ImageSaver可以通过该界面将图片传回Activity以显示在ImageView中。

public interface OnImageDecodedListener {
    public void onImageDecoded(Bitmap b);
}

然后我们需要稍微更改ImageSaver类以在构造函数中获取Activity参数。我还添加了File参数,因此Activity的相应字段不必是static

private static class ImageSaver implements Runnable {
    private final Activity mActivity;
    private final Image mImage;
    private final File mImageFile;

    public ImageSaver(Activity activity, Image image, File imageFile) {
        mActivity = activity;
        mImage = image;
        mImageFile = imageFile;
    }

    @Override
    public void run() {
        ByteBuffer byteBuffer = mImage.getPlanes()[0].getBuffer();
        byte[] bytes = new byte[byteBuffer.remaining()];
        byteBuffer.get(bytes);

        final Bitmap b = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ((OnImageDecodedListener) mActivity).onImageDecoded(b);
                }
            }
        );

        FileOutputStream fileOutputStream = null;
        ...
    }
}

只要我们在字节数组中获取图像数据,我们就会对其进行解码并将其传递回Activity,因此它不必等待文件写入,这可以在文件中安静地进行。背景。我们需要在UI线程上调用接口方法,因为我们在那里“触摸”View

Activity需要实现界面,我们可以将View相关内容从takePhoto()移动到onImageDecoded()方法。

public class MainActivity extends Activity
    implements ImageSaver.OnImageDecodedListener {
    ...

    @Override
    public void onImageDecoded(Bitmap b) {
        final ImageView latest_picture =
            (ImageView) findViewById(R.id.latest_picture);
        final RelativeLayout latest_picture_container =
            (RelativeLayout) findViewById(R.id.latest_picture_container);

        latest_picture.setImageBitmap(b);
        latest_picture_container.setVisibility(View.VISIBLE);
    }

    public void takePhoto(View view) {
        try {
            mImageFile = createImageFile();
            captureStillImage();
            lockFocus();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    ...
}

最后,我们需要在ImageSaver的{​​{1}}方法中实际执行ImageReader。再次按照这个例子,它就是这样的。

onImageAvailable()

答案 1 :(得分:0)

我通常使用Picasso库

将依赖项添加到build.gradle

compile 'com.squareup.picasso:picasso:2.5.2'

由于您要获取文件路径,请将路径设置为File对象,然后让Picasso从手机中获取图像,并将其设置为所需的ImageView

File fileLocation = new File(uri) //file path, which can be String, or Uri

Picasso.with(this).load(fileLocation).into(imageView);

我建议您将Picasso用于应用中的任何类型的图像活动,无论是在线还是离线。毕加索是由Square制作的,在图像加载,缓存方面是最好的......

答案 2 :(得分:0)

public static String getEDirectory(String folderName,Activity activity) {
    if(Environment.MEDIA_MOUNTED.equalsIgnoreCase(Environment.getExternalStorageState())){
        LogUtils.e( activity.getExternalFilesDir(folderName).getAbsolutePath());
        return activity.getExternalFilesDir(folderName).getAbsolutePath();
    }else{
        return activity.getFilesDir().getAbsolutePath() +File.separator+folderName;
    }
}    
public static Uri getImageUri(String shortname,Activity activity) {

    if (shortname == null) {
        shortname = "www.jpg";
    }
    String path = DataStore.getEDirectory("pure",activity);
    File files = new File(path);
    files.mkdirs();

    File file = new File(path, shortname);
    return Uri.fromFile(file);

}
    public static Uri attemptStartCamera(Activity ctx){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        String latestfilename = System.currentTimeMillis() + ".jpg";
        Uri imageUri = getImageUri(latestfilename,ctx);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        ctx.startActivityForResult(intent, MsgCodes.PICK_CAMERA);
        return imageUri;
    }

活动:

mUri = attemptStartCamera(Activity.this);

通过这种方式,你得到了Uri。

您可以在onActivityResult中加载图片:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==MsgCodes.PICK_CAMERA && resultCode == RESULT_OK){
        mImageView.setImageUri(mUri);
    }
}

答案 3 :(得分:0)

尝试这个简单的代码

ImageView imgView = view.findViewById(R.id.lw_foto);

imgView.setImageURI(mListaContactos.get(i).foto);