2012-09-05 32 views
3

我需要將2d整數數組(subSrc)轉換爲位圖。任何解決方案如何將2d int數組轉換爲位圖android

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); <---- ?? 

回答

0

可以使用 setPixel(int, int, int)setPixels (int[] pixels, int offset, int stride, int x, int y, int width, int height) methos OD Bitmap類。

 Bitmap dest = Bitmap.createBitmap(
     src.getWidth()/2, src.getHeight()/2, src.getConfig()); 

    int bmWidth = src.getWidth(); 
    int bmHeight = src.getHeight(); 


     for(int k = 0; k < bmWidth/2; k++){ 
     for(int l = 0; l < bmHeight/2; l++){ 
     dest.setPixel(k,l,src.getPixel(2*k, 2*l)); 

但我認爲這會更慢。

你uhave做這樣的事情

int subSrc = new int[(bmWidth/2*)(bmHeight/2)]; 
     for(int k = 0; k < bmWidth-2; k++){ 
     subSrc[k] = src.getPixel(2*(k/bmWidth), 2*(k%bmHeight)); <---- ?? 
0

所以第二個方法,你基本上是試圖拉出來的像素,做一些給他們,然後做一個位圖的結果呢?

例程期望的像素是在一維數組,所以你會希望把它們放入數組更是這樣的:

int data[] = new int[size]; 
data[x + width*y] = pixel(x,y); 
... 

然後使用Bitmap.createBitmap(),它接受一維數組。在你的例子中你會想用ARGB的Bitmap.Config,因爲你使用的是b.getPixel(x,y),它總是返回ARGB格式的顏色。

Bitmap result = Bitmap.createBitmap(data, width, height, Bitmap.Config.ARGB_8888); 
5

我尋找所接收的2D陣列的方法(INT [] [])和創建的位圖,並沒有發現,所以我寫一個自己:

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); 
} 

我也寫一個反向法:

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; 
} 

我希望你覺得它有用!