首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >压缩Uri图像并上传Firebase存储

压缩Uri图像并上传Firebase存储
EN

Stack Overflow用户
提问于 2019-04-17 23:44:18
回答 1查看 0关注 0票数 0

AccountActivity我的Android应用程序中,用户可以更改他/她的配置文件设置(如图像,名称,电子邮件等)。

我编写的代码将获取用户选择的图像的URI,并将其上传到Firebase存储,然后获取其下载URL并将其存储在Cloud Firestore中。

但在将图像上传到存储之前,我想压缩图像Uri,然后将原始图像和压缩图像上传到存储。最后,我想下载压缩图像的Url以在活动中显示它。

我尝试了很多代码,这段代码是我尝试过的最后一段代码:

代码语言:javascript
复制
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY_REQUEST_CODE && resultCode == RESULT_OK) {

            accountImageProgressBar.setVisibility(View.VISIBLE);

            Uri fileUri = data.getData();

            StorageReference accountImagesReferences = storageReference.child("Users Images").child(userID + "/" + fileUri.getLastPathSegment());

            Bitmap bitmap = ((BitmapDrawable) accountImage.getDrawable()).getBitmap();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] bytes = baos.toByteArray();

            // Upload To Storage
            UploadTask uploadTask = accountImagesReferences.putBytes(bytes);
            uploadTask

                    .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {

                    accountImageProgressBar.setVisibility(View.INVISIBLE);
                    Toast.makeText(AccountActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();

                }
            })

                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    accountImageProgressBar.setVisibility(View.INVISIBLE);
                    Toast.makeText(AccountActivity.this, "Upload Success", Toast.LENGTH_SHORT).show();

                }
            });

            // Get Download Url
            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();

                    }

                    // Continue with the task to get the download URL
                    return accountImagesReferences.getDownloadUrl();

                }
            })
                    .addOnCompleteListener(new OnCompleteListener<Uri>() {
                        @Override
                        public void onComplete(@NonNull Task<Uri> task) {

                            if (task.isSuccessful()) {

                                Uri downloadUri = task.getResult();
                                firebaseFirestore.collection("Users").document(userID).update("image", downloadUri.toString());
                                loadInfo(userID);

                            } else {

                                Toast.makeText(AccountActivity.this, "Task Not Successful", Toast.LENGTH_SHORT).show();

                            }

                        }
                    });

        }

    }

EN

回答 1

Stack Overflow用户

发布于 2019-04-18 09:30:13

这将完全符合您的要求。如果不是,那是因为“用户”没有通过firebase进行身份验证,因此您需要使用电子邮件或匿名身份验证进行注册

代码语言:javascript
复制
private static final int RESULT_GALLERY = 1;
private Uri imageUri;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent, RESULT_GALLERY);
        }
    });
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case RESULT_GALLERY:
            if (null != data) {
                imageUri = data.getData();
                UploadImages();
            }
            break;
        default:
            break;
    }
}
private byte[] compress(Uri image){
    Uri selectedImage = image;

    InputStream imageStream = null;
    try {
        imageStream = getContentResolver().openInputStream(
                selectedImage);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    Bitmap bmp = BitmapFactory.decodeStream(imageStream);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    bmp.compress(Bitmap.CompressFormat.JPEG, 20, stream);
    byte[] byteArray = stream.toByteArray();
    try {
        stream.close();
        stream = null;
        return byteArray;
    } catch (IOException e) {

        e.printStackTrace();
    }

    return null;
}

public void UploadImages() {
     final StorageReference ref = FirebaseStorage.getInstance().getReference().child("/images/");
    //Uploading original file.
    UploadTask uploadTask = ref.putFile(imageUri);
    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();
            }

            // Continue with the task to get the download URL
            return ref.getDownloadUrl();
        }
    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
        @Override
        public void onComplete(@NonNull Task<Uri> task) {
            //Original file download url.
            final StorageReference ref2 = FirebaseStorage.getInstance().getReference().child("Compressed");

            String downloadUri = String.valueOf(task.getResult());
            //Uploading compressed file.
            byte[] data = compress(imageUri);
            UploadTask uploadTask = ref2.putBytes(data);
            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();
                    }

                    // Continue with the task to get the download URL
                    return ref2.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    //Compressed file download url
                    String downloadUri = String.valueOf(task.getResult());

                }
            });
        }
    });
}

}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100006641

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档