Search code examples
androidcodenameone

Rotate an image in Android instantly (or almost)


I develop with Codename One and know how to rotate an image.

The problem is that the rotation of a photograph as returned by the camera or gallery (i.e. at maximum resolution) takes a variable time (about 5 seconds or more) on my Samsung Galaxy A20 (Android 10).

When I talk about rotations, I always refer to rotations of 90 degrees or multiples of 90 degrees.

I hope there are more efficient ways to rotate a high resolution image, e.g. by having the GPU do the work rather than the CPU. That's why I ask you Android programmers: do you have a code that can rotate a high-resolution image instantly or almost instantly?

As regards Codename One, for those who don't know it, it is possible to use native Android code, that's why I'm addressing you.


Solution

  • Which image type?

    If it's EncodedImage try to make it into a regular image first or at least lock() it. It's possible that the GC is thrashing the image out of RAM and you get repeated decode cycles. A 90 degree rotation should be pretty fast on a powerful device like that even for a very large image.

    So something like this should be pretty fast:

    img.lock();
    Image rotated; 
    switch(degrees)) {
       case 90: 
          rotated = img.rotate90Degrees();
          break;
       case 180: 
          rotated = img.rotate180Degrees();
          break;
       case 270: 
          rotated = img.rotate270Degrees();
          break;
       default: 
          rotated = img.rotate(degrees);
          break;
    }
    img.unlock();
    

    I suggest benchmarking this if this takes too long to figure the exact method that takes up CPU time. This should all perform very fast.