如何在Android中将二维整数数组转换为位图

5

我需要将一个二维整数数组(subSrc)转换为位图。有什么解决方案吗?

    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); <---- ??
3个回答

11

我寻找了一个接收2D数组(int [] [])并创建Bitmap的方法,但没有找到,所以我自己写了一个:

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

我希望你会觉得它有用!


0

你可以使用 Bitmap 类的 setPixel(int, int, int)setPixels (int[] pixels, int offset, int stride, int x, int y, int width, int height) 方法。

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

但我认为这样会慢一些。

对于第二种方法,您需要做类似于这样的事情

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接