【问题标题】:Unable to decode stream: java.io.FileNotFoundException: No such file or directory)无法解码流:java.io.FileNotFoundException:没有这样的文件或目录)
【发布时间】:2019-08-16 10:09:36
【问题描述】:

我正在尝试在将文件上传到 firebese 之前对其进行压缩。

不幸的是,没有任何事情发生:无法解码流: java.io.FileNotFoundException: /com.marijan.red.MessageActivity@dac48b3/document/image:256(没有这样的 文件或目录)

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GALLERY_PICK && resultCode == RESULT_OK){
           Uri imageUri = data.getData();

            DatabaseReference user_message_push = reference.child("Chats")
                    .child(fuser.getUid()).child(userid).push();

            final String push_id = user_message_push.getKey();

            final StorageReference filePath = mImageStorage.child("message_images").child(push_id +"jpg");

            File actualImage = new File (imageUri.getPath());
            try {
                Bitmap compressedImage = new Compressor(this)
                        .setQuality(50)
                        .compressToBitmap(actualImage);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                compressedImage.compress(CompressFormat.JPEG, 50, baos);
                byte[] final_image = baos.toByteArray();

                UploadTask uploadTask = filePath.putBytes(final_image);

                Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                    @Override
                    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                        if (!task.isSuccessful()) {
                            throw task.getException();
                        }


                        return filePath.getDownloadUrl();
                    }
                }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                    @Override
                    public void onComplete(@NonNull Task<Uri> task) {
                        if (task.isSuccessful()) {

                            String download_url = task.getResult().toString();

                            HashMap<String, Object> hashMap = new HashMap<>();
                            hashMap.put("sender", fuser.getUid());
                            hashMap.put("receiver",userid );
                            hashMap.put("message", download_url);
                            hashMap.put("isseen", false);
                            hashMap.put("type","image");

                            reference.push().setValue(hashMap);

我假设我没有正确传递 ImageUri

【问题讨论】:

  • 检查是否在运行时询问 READ_PERMISSION (SDK >= 23) & manifest
  • 您的imageUri 可以,但imageUri.getPath() 不行-它没有指向任何有效路径
  • 我该怎么做?

标签: android image compression chat


【解决方案1】:

你必须使用文件提供者[你可以从here]获得知识。或者你可以从你的uri 获取位图,你必须使用这样的内容解析器

Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);

所以现在您可以在上传之前压缩您的位图。

另一种方式uri 获取有效路径。它因设备操作系统而异。你可以打电话。 这里的路径是字符串

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
             path = getImageRealPath(getContentResolver(), uri, null);
  } else {
      path = uri.getPath();
   }

private String getImageRealPath(ContentResolver contentResolver, Uri uri, String whereClause) {
        String ret = "";

        // Query the uri with condition.
        Cursor cursor = contentResolver.query(uri, null, whereClause, null, null);

        if (cursor != null) {
            boolean moveToFirst = cursor.moveToFirst();
            if (moveToFirst) {

                // Get columns name by uri type.
                String columnName = MediaStore.Images.Media.DATA;
                Log.d("UriTest: ", "uri: " + uri);
                if (uri == MediaStore.Images.Media.EXTERNAL_CONTENT_URI) {
                    columnName = MediaStore.Images.Media.DATA;
                }


                // Get column index.
                int imageColumnIndex = cursor.getColumnIndex(columnName);

                // Get column value which is the uri related file local path.
                ret = cursor.getString(imageColumnIndex);
            }
        }

        return ret;
    }

注意:您必须先检查存储读取权限。

【讨论】:

  • Uri imageUri = data.getData(); uri压缩后有什么办法可以清除它?
  • 你的 imageUri 是一个局部变量。所以会被清除。这个局部变量也在 onActivityResult 中使用。因此,当 onActivityResult 调用时, imageUri 将在有效条件下被调用。所以 imageUri 将在每个 onActivityResult 调用中使用有效条件..
  • 我设法发送和压缩图像,但现在我有一个问题,我只能在图像上发送。当我第二次尝试时,我没有处理正在发送的图像,但是当我关闭活动并再次打开它并尝试发送它发送的图像时。一定有什么问题,也许当我发送第一张图片时,第二张图片 uri 只是第一次添加了一个
  • 这将取决于您的代码、您如何通过按钮单击或其他方式拍摄图像。或者您是否拍摄多张图像。我不知道你为拍摄的图像写了什么。但是在这个线程中,您的问题是找不到文件异常如果我的回答解决了您的问题,那么您可以接受。
【解决方案2】:

我是这样解决的: 现在我有一个新问题。我只能上传一张图片,然后我必须关闭活动并再次打开它以发送新的。我假设第一张图片的 imageuri 保持保存并添加到第一张图片上

 private String getRealPathFromURI(Uri contentURI) {
    String result;
    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        result = contentURI.getPath();
    } else {
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;

}
 public  boolean isWriteStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted2");
            return true;
        } else {

            Log.v(TAG,"Permission is revoked2");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted2");
        return true;
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == GALLERY_PICK && resultCode == RESULT_OK){
        Uri selectedImageURI = data.getData();
        File imageFile = new File(getRealPathFromURI(selectedImageURI));

        DatabaseReference user_message_push = reference.child("Chats")
                .child(fuser.getUid()).child(userid).push();
        final String push_id = user_message_push.getKey();

        final StorageReference filePath = mImageStorage.child("message_images").child(push_id +"jpg");

        try {
            Bitmap compressedImage = new Compressor(this)
                    .setQuality(50)
                    .compressToBitmap(imageFile);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            compressedImage.compress(Bitmap.CompressFormat.JPEG, 50, baos);
            final byte[] finalImage = baos.toByteArray();

            UploadTask uploadTask = filePath.putBytes(finalImage);
            Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                @Override
                public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                    if (!task.isSuccessful()) {
                        throw task.getException();
                    }


                    return filePath.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    if (task.isSuccessful()) {

                        String download_url = task.getResult().toString();

                        HashMap<String, Object> hashMap = new HashMap<>();
                        hashMap.put("sender", fuser.getUid());
                        hashMap.put("receiver",userid );
                        hashMap.put("message", download_url);
                        hashMap.put("isseen", false);
                        hashMap.put("type","image");

                        reference.push().setValue(hashMap);

【讨论】:

    猜你喜欢
    • 2019-11-11
    • 1970-01-01
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多