首页 > 解决方案 > 尽管指定了文件扩展名,但上传到 Cloud Storage 的文件类型不正确

问题描述

当我将图像上传到 Cloud Storage 时,我记得指定我要上传 PNG 文件,但它仍然上传 JPEG。

String privatePath = "privateFoodImages/" + mAuth.getCurrentUser().getUid() + "/" + UUID.randomUUID() + ".png"; 
final StorageReference privateReference = firebaseStorage.getReference(privatePath);

奇怪的是,它只在模拟器上这样做。当我在我的实际设备上测试相同的代码和安全规则时,它可以工作,采用我指定的任何文件扩展名并将其转换为 PNG。但它不会在模拟器上转换为 PNG。知道是什么原因造成的吗?

这是 Cloud Storage 中的两张图片。第一个来自模拟器,第二个来自我的设备。

标签: javaandroid-studiofirebase-storage

解决方案


我在这方面做了更多工作,并找到了解决方案。正如@drum 在我的原始评论下方指出的那样,它是数据库中的 PNG,因为我在上传之前没有将其转换为 PNG。这很奇怪,因为在我的设备上,我可以只指定 .png,剩下的就交给它了。对于那些苦苦挣扎的人,这是我现在正在使用的工作代码。

    // This paragraph will compress the image into a JPEG
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        selectedImage.compress(Bitmap.CompressFormat.JPEG, 50, bos);
        byte[] bitmapData = bos.toByteArray();



    // This paragraph will turn the compressed image back into the superior file type (PNG)
       Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapData, 0, bitmapData.length);
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
       byte[] pngByteArray = baos.toByteArray();

然后您可以使用 byte[] pngByteArray 并将其上传到云存储<STORAGE_REFERENCE>.putBytes(pngByteArray);


推荐阅读