读取android中图像的所有像素块的准确颜色

问题描述 投票:0回答:2

我有一个图像,它的像素在网格块中。每个像素占据一个网格的20x20px块。这是图像

enter image description here

我想读取该网格的每个块的颜色。这是我试过的代码。

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.abc);
    for(int y=0; y<bmp.getHeight(); y=y+20){
      for(int x=0; x<bmp.getWidth(); x=x+20){  
        pixelColor = bmp.getPixel(x,y);
    }
      }

现在的问题是,正在读取的颜色有很小的差异,结果它选择了太多的颜色。例如,在黑色的情况下,它挑选了几乎10种黑色,这些颜色彼此略有不同。请帮我挑选所有独特的颜色。任何帮助将非常感激。谢谢

java android android-studio bitmap rgb
2个回答
0
投票

这是设备密度的问题。您应该为不同密度的设备放置不同尺寸的图像。由于您的图像读取超过实际宽度和高度。这导致问题将循环重载到实际像素以上。

看看https://developer.android.com/guide/practices/screens_support.html#qualifiers看到不同的密度设备放置各种drawable。如果您需要在UI中显示它,则需要这样做。

否则,如果您不希望图像在UI中显示。将图像放在drawable-nodpi文件夹中并获取高度,宽度,它将返回正确的结果。

看到这个Question&我从这个Solution引用

更新:

    ImageView imgTop = (ImageView) findViewById(R.id.imgTop);
    ImageView imgBtm = (ImageView) findViewById(R.id.imgBtm);

    Bitmap bmp1 = BitmapFactory.decodeResource(getResources(), R.drawable.pixel);

    Bitmap output = Bitmap.createBitmap(bmp1.getWidth(),bmp1.getHeight(), Bitmap.Config.ARGB_8888);

    int count = 0;
    int[] pixelColor = new int[bmp1.getHeight() * bmp1.getHeight()];
    for(int y=0; y<bmp1.getHeight(); y++){
        for(int x=0; x<bmp1.getWidth(); x++){
           pixelColor[count] = bmp1.getPixel(x,y);

            if(Color.red(pixelColor[count]) <= 30 && Color.green(pixelColor[count]) <= 30 && Color.blue(pixelColor[count]) <= 30)
            {
                pixelColor[count] = Color.BLACK;
            }
            else
            {
               //pixelColor[count] contain other colours..
            }
            output.setPixel(x,y,pixelColor[count]);
            count++;
        }
    }

    imgTop.setImageBitmap(bmp1);
    imgBtm.setImageBitmap(output);

OUTPUT

enter image description here


0
投票

我终于通过在android中使用Palette类来弄清楚自己

我已经使用它的嵌套类Palette.Swatch来获取图像中的所有颜色样本。这是我如何做到这一点

ArrayList<Integer> color_vib = new ArrayList<Integer>();
Bitmap bitmap = BitmapFactory.decodeResource( getResources(), R.drawable.abc );
Palette.from( bitmap ).generate( new Palette.PaletteAsyncListener() {
  @Override
     public void onGenerated( Palette palette ) {
            //work with the palette here
             for( Palette.Swatch swatch : palette.getSwatches() ) {
                    color_vib.add( swatch.getRgb() );
                }
        }
    });

现在我有任何块状像素化图像的所有独特颜色:)

© www.soinside.com 2019 - 2024. All rights reserved.