我正在尝试将图片上传到Firebase,但是当图片尺寸很大时会出现OOM错误。我试图使用一些库,比如滑行,但我没有减小尺寸。
以下是将URI更改为位图的代码:
public byte[] getBytesFromUri(Uri uri, int quality) {
ByteArrayOutputStream stream=new ByteArrayOutputStream();
Bitmap bitmap=null;
try {
bitmap=MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
} catch (IOException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
return stream.toByteArray();
}
这是上传到firebase部分:
StorageReference file2path=mStorage.child("products_images").child(mAuth.getCurrentUser().getUid()).child(nouveau_produit.getKey()).child("image_2");
file2path.putBytes(getBytesFromUri(resultUri2, 100)).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri second_Dwn_Url=taskSnapshot.getDownloadUrl();
image2=second_Dwn_Url.toString().trim();
//images upload
nouveau_produit.child("image_2").setValue(image2);
nouveau_produit_category.child("image_2").setValue(image2);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(UploadActivity.this,"uploading of second image failed",Toast.LENGTH_LONG).show();
}
});
我上传的图片似乎很大。 这是应用程序崩溃时我遇到的错误:
FATAL EXCEPTION: main
Process: tk.a45developer.www.kukaguriro, PID: 13149
java.lang.OutOfMemoryError
at java.io.ByteArrayOutputStream.toByteArray(ByteArrayOutputStream.java:122)
at tk.a45developer.www.kukaguriro.UploadActivity.getBytesFromUri(UploadActivity.java:1294)
at tk.a45developer.www.kukaguriro.UploadActivity$10.onClick(UploadActivity.java:867)
at android.view.View.performClick(View.java:4508)
at android.view.View$PerformClick.run(View.java:18675)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5590)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1280)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1096)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
谢谢你们的评论我刚刚找到了一种方法来使用SiliCompressor库 这是我的代码,我使用sillycompressor库sillycompressor github link
将uri更改为位图public byte[] getBytesFromUri(Uri uri, int quality) {
ByteArrayOutputStream stream=new ByteArrayOutputStream();
Bitmap bitmap=null;
try {
bitmap = SiliCompressor.with(UploadActivity.this).getCompressBitmap(uri.toString());
} catch (IOException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
return stream.toByteArray();
}