首页 > 解决方案 > Picasso 无法从 Uri 加载位图 - ImageView 显示为黑色视图

问题描述

我正在使用自定义相机,当用户单击相机按钮时,它应该调用此方法。data参数是以字节为单位拍摄的图像。我希望这种方法可以从图像中制作位图,将其放入包中,然后将该包放入将显示图像的片段中。这是从我的Camera.PictureCallback.

public static void displayCameraImage(byte[] data) {
    BitmapFactory.Options scalingOptions = new BitmapFactory.Options();
    final Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length, scalingOptions);
    FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction();
    Fragment displayImageFragment = new DisplayImageFragment();
    Bundle bundle = new Bundle();
    bundle.putParcelable("image", bmp);
    displayImageFragment.setArguments(bundle);
    fragmentTransaction.add(R.id.flMainContainer, displayImageFragment, "confirmselfie");
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

onCreateView()里面的方法中,DisplayImageFragment我从包中获取位图并尝试使用 Picasso 加载它,如下所示:

Bitmap bmp = getArguments().getParcelable("image");
final Uri uri = getImageUri(getContext(), bmp);
Picasso.with(getActivity()).load(uri).into(ivImage, new ImageLoadedCallback(progressBar) {
            @Override
            public void onSuccess() {
                if (this.progressBar != null) {
                    this.progressBar.setVisibility(View.GONE);
                }
            }
        });

出于某种原因,这不会显示拍摄的图像 - 相反,它会显示一个黑色的 ImageView。有谁知道为什么会发生这种情况?感谢任何努力。

编辑:如果有人感兴趣,getImageUri()方法在这里:

public Uri getImageUri(Context context, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), inImage, "confirmSelfie", null);
    return Uri.parse(path);
}

我也尝试过从文件(new File("path"))加载,而不是直接传入 Uri。

标签: androidandroid-camerapicasso

解决方案


使用类似的东西,如果您无法加载 URI,则为 URI 创建一个文件。

File f = new File("path-to-file/file.png")

或者

File f = new File(uri)

Picasso.with(getActivity()).load(f).into(imageView);

推荐阅读