-2

I tried compressing my image in my android app by using:

Bitmap.compress(Bitmap.CompressFormat.JPEG, 40, byteArrayOutputStream);

But I am getting the above error. What's the best way for me to do this without experiencing the error?

Rahul Chokshi
  • 670
  • 4
  • 18
Tonye Boro
  • 313
  • 4
  • 15
  • 1
    *Search* for the error message (["non-static method cannot be referenced from a static context"](https://www.google.com/search?q=non-static+method+cannot+be+referenced+from+a+static+context)). *Read* about the cause (and how to use instance methods). *Apply* new knowledge. Finish program. Win. – user2864740 Sep 03 '18 at 04:23
  • did you call this line in static method? – sasikumar Sep 03 '18 at 04:24
  • Did you ever wonder which bit map would be compressed by your code line? – Henry Sep 03 '18 at 04:24
  • 1
    Possible duplicate of [What is the reason behind "non-static method cannot be referenced from a static context"?](https://stackoverflow.com/questions/290884/what-is-the-reason-behind-non-static-method-cannot-be-referenced-from-a-static) – Henry Sep 03 '18 at 04:28

1 Answers1

1

The compress() method of Bitmap is an "instance method" (as opposed to a "static method"). This means that it must be invoked on an actual existing Bitmap object, rather than on the Bitmap class itself.

In other words:

Bitmap uncompressed = /* some bitmap you've gotten from somewhere */
ByteArrayOutputStream out = new ByteArrayOutputStream();
uncompressed.compress(..., out);
Bitmap compressed = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

Here were are invoking compress() on the uncompressed bitmap instance.

On some level, this makes intuitive sense. If you were able to simply write:

Bitmap compressed = Bitmap.compress(...);

Then you'd have to ask yourself: what are you compressing?

Ben P.
  • 52,661
  • 6
  • 95
  • 123
  • `Bitmap compressed = uncompressed.compress(...)` - the method `compress` returns a `boolean`, not a `Bitmap`. – Nabin Bhandari Sep 03 '18 at 04:41
  • 1
    You're right, sorry. The third argument to the `compress()` method is an `OutputStream` that receives the compressed bitmap. – Ben P. Sep 03 '18 at 04:43