15

i've a bitmap that i want to change certain pixels. i've got the data from the bitmap into an array, but how would i set a pixels colour in that array?

thanks

int[] pixels = new int[myBitmap.getHeight()*myBitmap.getWidth()];
            myBitmap.getPixels(pixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());

            for(int i =0; i<500;i++){
                //Log.e(TAG, "pixel"+i +pixels[i]);
turtleboy
  • 8,210
  • 27
  • 100
  • 199

1 Answers1

27

To set the colors of the pixels in your pixels array, get values from the static methods of Android's Color class and assign them into your array. When you're done, use setPixels to copy the pixels back to the bitmap.

For example, to turn the first five rows of the bitmap blue:

import android.graphics.Color;

int[] pixels = new int[myBitmap.getHeight()*myBitmap.getWidth()];
myBitmap.getPixels(pixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());
for (int i=0; i<myBitmap.getWidth()*5; i++)
    pixels[i] = Color.BLUE;
myBitmap.setPixels(pixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());

You can also set a pixel's color in a Bitmap object one at a time without having to set up a pixel buffer with the setPixel() method:

myBitmap.setPixel(x, y, Color.rgb(45, 127, 0));
BHSPitMonkey
  • 654
  • 5
  • 14
  • 1
    how to do this to get all pixels – Sheychan Aug 19 '15 at 09:51
  • @Sheychan if I does not get you wrong, BHSPitMonkey created a empty pixels array with size equal to total number of pixels first. Then myBitmap is some bitmap you obtained from drawable to bitmap. this myBitmap.getPixels first parameter pixels is the array we just created and then finally this pixels array will be updated with colors of what myBitmap store. – Raii Jul 07 '22 at 04:11