图片加载缓慢 – 使用 Picasso 和 Firebase 在 Android Studio 中的 Java。

huangapple go评论83阅读模式
英文:

Slow loading of pictures - using picaso and Firebase Android Studio Java

问题

这是您的代码:

在用户信息中加入以下部分:

private void sendUserData() {
    // ...(之前的代码)
    // 在这里添加图片压缩和上传的代码
}

图片上传部分:

private void UpdateUserInfo(final String name, Uri pickedimguri, final FirebaseUser currnetUser) {
    // ...(之前的代码)

    // 在这里添加图片压缩和上传的代码
    // 可以使用Bitmap和ByteArrayOutputStream进行图片压缩,然后将压缩后的字节数组上传至Firebase Storage

    // 压缩图片
    Bitmap bitmap = BitmapFactory.decodeFile(pickedimguri.getPath());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
    byte[] data = baos.toByteArray();

    // 继续上传压缩后的图片数据
    imagefilepath.putBytes(data).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
            if (task.isSuccessful()) {
                imagefilepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
                                .setDisplayName(name)
                                .setPhotoUri(uri)
                                .build();
                        currnetUser.updateProfile(profileUpdate)
                                .addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if (task.isSuccessful()) {
                                            showMessage("Register complete");
                                        }
                                    }
                               });
                    }
                });
            }
        }
    });
}

加载用户信息部分:

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    // ...(之前的代码)
    // 在这里添加加载图片的代码,使用Picasso或Glide进行图片加载并显示
    // 请注意,这里加载图片的速度也会受到网络和图片大小的影响
}

注意:以上代码示例中添加了图片压缩的部分,以帮助减小图片的数据量,从而提高加载速度。压缩率和效果可以根据实际需要进行调整。另外,图片加载速度也会受到网络状况和图片大小的影响,无法完全消除加载延迟。

英文:

I created a profile for a user and i've got one problem:
The loading is slow - due to every pic is 4mb and it takes about 20 sec to load,
I need some help about image compression/methods to reduce data and make the program download the img and put it into the profile faster.

Im using android studio and java

this is my code:
Here im adding to the user some information

private void sendUserData() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myref = firebaseDatabase.getReference(firebaseAuth.getUid());
userProfile user = new userProfile(Sphone, Semail, name);// simple object  get and set 
myref.setValue(user);
UpdateUserInfo(name, pickedImgUri, firebaseAuth.getCurrentUser());
}

Here its uploading the image

private void UpdateUserInfo(final String name, Uri pickedimguri, final FirebaseUser currnetUser) {
StorageReference mStorageReference = FirebaseStorage.getInstance().getReference().child(&quot;users_photos&quot;);
final StorageReference imagefilepath = mStorageReference.child(pickedimguri.getLastPathSegment());
imagefilepath.putFile(pickedimguri).addOnCompleteListener(new OnCompleteListener&lt;UploadTask.TaskSnapshot&gt;() {
@Override
public void onComplete(@NonNull Task&lt;UploadTask.TaskSnapshot&gt; task) {
imagefilepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener&lt;Uri&gt;() {
@Override
public void onSuccess(Uri uri) {
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.setPhotoUri(uri)
.build();
currnetUser.updateProfile(profileUpdate)
.addOnCompleteListener(new OnCompleteListener&lt;Void&gt;() {
@Override
public void onComplete(@NonNull Task&lt;Void&gt; task) {
if (task.isSuccessful()) {
showMessage(&quot;Register complete&quot;);
}
}
});
}
});
}
});
}

And this is the loading code to the user profile after creating it and entering the main screen:

    @Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
name = getView().findViewById(R.id.textView);
profilepic = getView().findViewById(R.id.profilepic);
final String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference uidRef = rootRef.child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email = dataSnapshot.child(&quot;email&quot;).getValue(String.class);
String nameE = dataSnapshot.child(&quot;name&quot;).getValue(String.class);
String phone = dataSnapshot.child(&quot;phone&quot;).getValue(String.class);
Log.d(&quot;TAG&quot;, nameE + &quot;, &quot; + email + &quot;, &quot; + phone);
name.setText(&quot;Welcome &quot; + nameE);
Picasso.get().load(FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl().toString()).into(profilepic);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(&quot;TAG&quot;, databaseError.getMessage()); //Don&#39;t ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
}

Thanks!

答案1

得分: 0

以下是翻译好的内容:

这是一个压缩图像用于 Firebase 存储的示例。这是我正在使用的方法,它将图像从 2-4MB 之间压缩至小于 300KB。JPEG 是一种有损格式,我使用 75 的压缩级别,这仍然保留了图像中大部分的细节。

// 从图像的 URI 开始
if (uri != null) {
    Bitmap bmp = null;
    try {
        bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
    } catch (IOException e) {
        e.printStackTrace();
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 75, baos);
    byte[] bytes = baos.toByteArray();
    StorageReference reference = FirebaseStorage.getInstance().getReference("放置图像的文件夹/" + 图像的名称 + ".jpg");
    UploadTask uploadTask = reference.putBytes(bytes);

    uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onProgress(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
            // 上传进度监听
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // 上传失败监听
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            // 上传成功监听
        }
    });
}
英文:

Here's an example of compressing an image for firebase storage. This is the method I'm using, and it reduces images between 2-4mb down to <300kb. JPEG is a lossy format and I use a level of 75 for compression, which still retains most of the detail in an image.

//Start with URI of image
if (uri != null) {
Bitmap bmp = null;
try {
bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 75, baos);
byte[] bytes = baos.toByteArray();
StorageReference reference = FirebaseStorage.getInstance().getReference(&quot;whatever folder you place the images in/&quot; + name_of_image + &quot;.jpg&quot;);
UploadTask uploadTask = reference.putBytes(bytes);
uploadTask.addOnProgressListener(new OnProgressListener&lt;UploadTask.TaskSnapshot&gt;() {
@Override
public void onProgress(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
}
}).addOnSuccessListener(new OnSuccessListener&lt;UploadTask.TaskSnapshot&gt;() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}

huangapple
  • 本文由 发表于 2020年4月9日 06:50:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/61111283.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定