java - 设置图像 uri 给出无法解码流 : java. io.FileNotFoundException:

标签 java android firebase firebase-storage

我有一个简单的应用程序,可以使用以下代码使用相机捕获图像

@AfterPermissionGranted(RC_STORAGE_PERMS)
private void launchCamera() {
    Log.d(TAG, "launchCamera");

    // Check that we have permission to read images from external storage.
    String perm = android.Manifest.permission.READ_EXTERNAL_STORAGE;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
            && !EasyPermissions.hasPermissions(this, perm)) {
        EasyPermissions.requestPermissions(this, getString(R.string.rationale_storage),
                RC_STORAGE_PERMS, perm);
        return;
    }

    // Create intent
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    // Choose file storage location
    File file = new File(Environment.getExternalStorageDirectory(), UUID.randomUUID().toString() + ".jpg");
    mFileUri = Uri.fromFile(file);
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);

    // Launch intent
    startActivityForResult(takePictureIntent, RC_TAKE_PICTURE);
}

现在我想将该图片上传到 Firebase 存储

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
    if (requestCode == RC_TAKE_PICTURE) {
        if (resultCode == RESULT_OK) {
            if (mFileUri != null) {
                uploadFromUri(mFileUri);
            } else {
                Log.w(TAG, "File URI is null");
            }
        } else {
            Toast.makeText(this, "Taking picture failed.", Toast.LENGTH_SHORT).show();
        }
    }
}

private void uploadFromUri(Uri fileUri) {
    Log.d(TAG, "uploadFromUri:src:" + fileUri.toString());

    // [START get_child_ref]
    // Get a reference to store file at photos/<FILENAME>.jpg
    final StorageReference photoRef = mStorageRef.child("photos")
            .child(fileUri.getLastPathSegment());
    // [END get_child_ref]

    // Upload file to Firebase Storage
    // [START_EXCLUDE]
    showProgressDialog();
    // [END_EXCLUDE]
    Log.d(TAG, "uploadFromUri:dst:" + photoRef.getPath());
    photoRef.putFile(fileUri)
            .addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    // Upload succeeded
                    Log.d(TAG, "uploadFromUri:onSuccess");

                    // Get the public download URL
                    mDownloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
                    Log.w("IMAGE_URL", "Path is " + mDownloadUrl.toString());
                    uploadedImage = (ImageView) findViewById(R.id.uploaded_img);

                    try{// Here I'm setting image in ImageView                            
                        uploadedImage.setImageURI(mDownloadUrl);
                    }catch (Exception e){
                        System.out.print(e.getCause());
                    }

                    // [START_EXCLUDE]
                    hideProgressDialog();
                    ///updateUI(mAuth.getCurrentUser());
                    // [END_EXCLUDE]
                }
            })
            );
}

在 uploadFromUri() 行中

try{// Here I'm setting image in ImageView                            
    uploadedImage.setImageURI(mDownloadUrl);
}catch (Exception e){
    System.out.print(e.getCause());
}

ImageView 中未设置图像,出现错误

07-29 09:54:23.055 18445-18445/? W/IMAGE_URL: Path is https://firebasestorage.googleapis.com/v0/b/connectin-a74da.appspot.com/o/photos%2F7dd3d46f-ed7b-4020-bc89-fd9e19a8ec65.jpg?alt=media&token=5b4f9ad7-1e99-42b8-966d-50c74fc2eab6
07-29 09:54:23.056 18445-18445/? E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: https:/firebasestorage.googleapis.com/v0/b/connectin-a74da.appspot.com/o/photos%2F7dd3d46f-ed7b-4020-bc89-fd9e19a8ec65.jpg?alt=media&token=5b4f9ad7-1e99-42b8-966d-50c74fc2eab6: open failed: ENOENT (No such file or directory)

如果我打开此链接,我会在那里看到图像,问题是为什么它没有在 ImageView 中设置

最佳答案

setImageURI() 用于 Android 特有的内容 URI 平台,而不是指定 Internet 资源的 URI。

尝试在新线程中从互联网获取位图,然后将其添加到您的 ImageView 中。像这样:

uploadedImage.setImageBitmap(getImageBitmap(mDownloadUrl));


private Bitmap getImageBitmap(String url) {
        Bitmap bm = null;
        try {
            URL aURL = new URL(url);
            URLConnection conn = aURL.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
       } catch (IOException e) {
           Log.e(TAG, "Error getting bitmap", e);
       }
       return bm;
    } 

您还可以使用一个有用的库来设置图像(内部和外部图像),称为 Picasso http://square.github.io/picasso/

关于java - 设置图像 uri 给出无法解码流 : java. io.FileNotFoundException:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38654333/

相关文章:

android - 在 "managed"购买类型上卸载后应用内购买丢失

c# - 如何运行Main.axml?

java - 为什么example中的 "@override"before functions报错?

java - 新实体和现有实体的级联插入

某些设备上的 Play 商店中未显示 Android 应用

iOS : Firebase notification not working for user segment

javascript - 等到 Firebase 读取列表完成后再返回记录数组

Java 7 : An array as input

java - java实现TCP server和TCP client传输文件的方法

javascript - Firebase google auth 未完全注销