Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert 2d int array to bitmap in android

Tags:

android

I need to convert a 2d integer array (subSrc) to a bitmap. Any solutions?

    private Bitmap decimation(Bitmap src){
     Bitmap dest = Bitmap.createBitmap(
       src.getWidth(), src.getHeight(), src.getConfig());

     int bmWidth = src.getWidth();
     int bmHeight = src.getHeight();`enter code here`

int[][] subSrc = new int[bmWidth/2][bmWidth/2];
       for(int k = 0; k < bmWidth-2; k++){
        for(int l = 0; l < bmHeight-2; l++){
         subSrc[k][l] = src.getPixel(2*k, 2*l); <---- ??
like image 359
Redman Avatar asked Sep 05 '12 03:09

Redman


1 Answers

I looked for a method that received an 2d array (int[][]) and created a Bitmap, and found none, so I wrote one myself:

public static Bitmap bitmapFromArray(int[][] pixels2d){
    int width = pixels2d.length;
    int height = pixels2d[0].length;
    int[] pixels = new int[width * height];
    int pixelsIndex = 0;
    for (int i = 0; i < width; i++)
    {
        for (int j = 0; j < height; j++)
        {
               pixels[pixelsIndex] = pixels2d[i][j];
               pixelsIndex ++;
        } 
    }
    return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888);
}

I also wrote a reverse method:

public static int[][] arrayFromBitmap(Bitmap source){
int width = source.getWidth();
int height = source.getHeight();
int[][] result = new int[width][height];
int[] pixels = new int[width*height];
source.getPixels(pixels, 0, width, 0, 0, width, height);
int pixelsIndex = 0;
for (int i = 0; i < width; i++)
{
    for (int j = 0; j < height; j++)
    {
      result[i][j] =  pixels[pixelsIndex];
      pixelsIndex++;
    }
}
return result;
}

I hope you find it useful!

like image 137
alexander zak Avatar answered Sep 17 '22 20:09

alexander zak