java - 尽管指定了文件扩展名,但上传到 Cloud Storage 的文件类型不正确
问题描述
当我将图像上传到 Cloud Storage 时,我记得指定我要上传 PNG 文件,但它仍然上传 JPEG。
String privatePath = "privateFoodImages/" + mAuth.getCurrentUser().getUid() + "/" + UUID.randomUUID() + ".png";
final StorageReference privateReference = firebaseStorage.getReference(privatePath);
奇怪的是,它只在模拟器上这样做。当我在我的实际设备上测试相同的代码和安全规则时,它可以工作,采用我指定的任何文件扩展名并将其转换为 PNG。但它不会在模拟器上转换为 PNG。知道是什么原因造成的吗?
第一个来自模拟器,第二个来自我的设备。
解决方案
我在这方面做了更多工作,并找到了解决方案。正如@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);
推荐阅读
- html - FullCalendar:更改事件的宽度
- javascript - 太多 React 组件重渲染,如何限制?
- multidimensional-array - 如何将 4、2 × 2 数组存储到更大的 4 × 4 数组中?
- node.js - 如何使用nodejs从猫鼬数组中的默认值中过滤
- python - RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 和 cpu
- java - 如何在命令行中通过 testName 运行单个测试?
- html - 当我悬停链接时,如何使此处的背景颜色不移动?
- mysql - 将处理与 SQL 数据库连接并获取列名
- c# - 从 XML 文件 C# 中获取 ID 属性列表
- c - 如何使用 write 显示字符串?