根据网络图片获取背景色,用Palette 获取出来的颜色总是不对。
Palette p = Palette.from(resource).generate();
int defaultColor =
ContextCompat.getColor(ClipActivity.this, android.R.color.holo_blue_bright);
int[] colors = new int[7];
colors[0] = p.getMutedColor(defaultColor);
colors[1] = p.getDarkMutedColor(defaultColor);
colors[2] = p.getLightMutedColor(defaultColor);
colors[3] = p.getVibrantColor(defaultColor);
colors[4] = p.getDarkVibrantColor(defaultColor);
colors[5] = p.getLightVibrantColor(defaultColor);
colors[6] = p.getDominantColor(defaultColor);
//
ll_data.removeAllViews();
// List<Palette.Swatch> swatches = p.getSwatches();
// for (Palette.Swatch swatch : swatches) {
// int rgb1 = swatch.getRgb();
// setTextBgColor(rgb1);
// }
// for (int color : colors) {
// setTextBgColor(color);
// }
int color4 = getBigColor(resource);
最后找了终于找到了代码(参考的代码地址忘记了)
1.缩小图片,2获取图片每个像素颜色最多的。
private static Bitmap small(Bitmap bitmap) {
Matrix matrix = new Matrix();
matrix.postScale(0.25f, 0.25f);
Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizeBmp;
}
public static ArrayList<Integer> getPicturePixel(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
// 保存所有的像素的数组,图片宽×高
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
ArrayList<Integer> rgb = new ArrayList<>();
for (int i = 0; i < pixels.length; i++) {
int clr = pixels[i];
int red = (clr & 0x00ff0000) >> 16; // 取高两位
int green = (clr & 0x0000ff00) >> 8; // 取中两位
int blue = clr & 0x000000ff; // 取低两位
// Log.d("tag", "r=" + red + ",g=" + green + ",b=" + blue);
int color = Color.rgb(red, green, blue);
//除去白色和黑色
if (color != Color.WHITE && color != Color.BLACK) {
rgb.add(color);
}
}
return rgb;
}
public static int getBigColor(Bitmap bitmap) {
ArrayList<Integer> picturePixel = getPicturePixel(small(bitmap));
//计数相同颜色数量并保存
HashMap<Integer, Integer> color2 = new HashMap<>();
for (Integer color : picturePixel) {
if (color2.containsKey(color)) {
Integer integer = color2.get(color);
integer++;
color2.remove(color);
color2.put(color, integer);
} else {
color2.put(color, 1);
}
}
//挑选数量最多的颜色
Iterator iter = color2.entrySet().iterator();
int count = 0;
int color = 0;
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
int value = (int) entry.getValue();
if (count < value) {
count = value;
color = (int) entry.getKey();
}
}
return color;
}