0

I'm fetching a remote image and I want to have two different Bitmaps but I'm not sure how to without fetching the image twice. If I use this code:

asyncTask(new GetRemoteImage(), (remoteImage) -> {
    Bitmap darkImage = darkImage(remoteImage);
});


private static Bitmap darkImage(Bitmap bm) {
    if (bm != null) {
        Canvas canvas = new Canvas(bm);
        canvas.drawARGB(175, 0, 0, 0);
        canvas.drawBitmap(bm, new Matrix(), new Paint());
    }
    return bm;
}

Both the remoteImage and darkImage are darkened. I'm not 100% sure but I'm guessing there's only one reference to remoteImage and darkImage points to remoteImage.

I can run the asyntask twice to get another image but not sure if there's a better way.

Kris B
  • 3,436
  • 9
  • 64
  • 106
  • 1
    Mind you, `darkImage` and `remoteImage` are the same object currently, it'd be strange if they were different. Try making a copy `bm = bm.copy(bm.getConfig(), true)`, before you do anything with `canvas`. Then you should end up returning the copied `Bitmap`. – Rogue Aug 15 '23 at 15:10
  • Does this answer your question? [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – knittl Aug 15 '23 at 15:19
  • `bm.copy` is what I was looking for. Thanks! – Kris B Aug 15 '23 at 15:20
  • For future reference, remember to show your imports so folks know which _specific_ class you're talking about, since there are typically lots of different packages that offer the same generically named classes with wildly different APIs. That said, it would be a good idea to still [edit] your post and do that here, since you're not just asking for yourself, but for every future visitor with the same question, and they should be able to tell whether you're using the same imports as they are. – Mike 'Pomax' Kamermans Aug 15 '23 at 15:36

1 Answers1

1

Both are being darkened because they both point to the same object. To create a copy of the remoteImage try this code before you call darkImage:

Bitmap remoteImageCopy = remoteImage.copy(remoteImage.getConfig(), remoteImage.isMutable())
Banana999
  • 73
  • 5