7

All,

After I noticed how slow getPixel and setPixel are (not sure which one, guess both are not turbocharged) I quickly coded a container for Bitmap that uses int[] array to handle bitmap operations.

Already - its noticeably faster, but this is not enough. Please could you advice how to speed it up further?

My idea is to keep track of what is made "dirty" by the setPixel functions and update only this part of Bitmap when getBitmap() is called ... not clear on how to set the setPixels parameters though (something with offset and stride I guess).

Also - any faster recipe?

Thanks for all help in advance!

import android.graphics.Bitmap;

public class DrawableBitmapContainer {
private Bitmap image;
private int width, height;
private int[]  pixels;
public DrawableBitmapContainer(Bitmap _source ){
    image = _source;
    width = image.getWidth();
    height = image.getHeight();
    pixels = new int[width*height];
    image.getPixels(pixels,0,width,0,0,width,height);
}
public int getPixel(int x,int y){
    return pixels[x+y*width];
}
public void setPixel(int x,int y, int color){
    pixels[x+y*width]=color;
}
public Bitmap getBimap(){
    image.setPixels(pixels,0,width,0,0,width,height);
    return image;
}
public int getWidth(){
    return image.getWidth();
}
public int getHeight(){
    return image.getHeight();
}
}
lucian.pantelimon
  • 3,673
  • 4
  • 29
  • 46
Piotr
  • 1,597
  • 3
  • 18
  • 25
  • I hope you realize that your bitmap takes a 2X memory footprint and also your setpixel does not work. This array is just a copy of the image matrix inside the actual bitmap. So by changing values in it, they don't get persisted until you commit that buffer back to the bitmap object. – Greg Giacovelli Jan 17 '11 at 19:40
  • I understand its twice the memory (worth the speed in my use) but I am lost with your comment that the setpixel does not work - it works if I am accessing the bitmap via getBitmap method and that is what I wanted. – Piotr Mar 26 '11 at 11:33
  • sure you trade memory footprint for performance which works really well if you have to transform every pixel on a larger bitmap – Kibotu Jul 18 '18 at 17:14

2 Answers2

5

For functions as simple as setPixel / getPixel, the function call overhead is relatively large.

It would be a lot faster to access the pixels array directly instead of through these functions. Of course that means you have to make pixels public, which isn't very nice from a design point of view, but if you absolutely need all the performance you can get, this is the way to go.

See also Designing for performance in the Android docs.

If this is still not enough, consider coding your bitmap operations in C++ using the NDK.

lucian.pantelimon
  • 3,673
  • 4
  • 29
  • 46
svdree
  • 13,298
  • 4
  • 28
  • 21
0

another alternative is using the android ndk. when it comes to that you have very little help but it really increases the speed

burakcoskun
  • 53
  • 2
  • 7