原理:bitmap.getPixel返回的是ARGB值,通过移位操作获取到R、G、B的值, 使用亮度=0.229×R + 0.587*G + 0.114*B进行亮度值计算, 将所有点的亮度值相加后取一个平均值, 如果这个值比128大,则这个图片较亮,如果这个值比128小,则这个图比较暗。 //java private int getBright(Bitmap bm) { Log.d(TAG, "getBright start"); if(bm == null) return -1; int width = bm.getWidth(); int height = bm.getHeight(); int r, g, b; int count = 0; int bright = 0; count = width * height; int[] buffer = new int[width * height]; bm.getPixels(buffer, 0, width, 0, 0, width , height); Log.d(TAG, "width:" + width + ",height:" + height); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { int localTemp = buffer[j * width + i];//bm.getPixel(i, j); r = (localTemp >> 16) & 0xff; g = (localTemp >> 8) & 0xff; b = localTemp & 0xff; bright = (int) (bright + 0.299 * r + 0.587 * g + 0.114 * b); } } Log.d(TAG, "getBright end"); return bright / count; } //c++ //定义 public int getBitmapBright(Bitmap bitmap) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); int[] buffer = new int[w * h]; bitmap.getPixels(buffer, 0, w, 0, 0, w, h); return getBitmapBrightByArr(buffer, w, h); } public native int getBitmapBrightByArr(int[] buffer, int width, int height); //实现 extern "C" JNIEXPORT jint JNICALL Java_com_zpy_wallpaperhsb_ImageNativeTool_getBitmapBrightByArr( JNIEnv *env, jobject /* this */, jintArray buffer, jint jwidth, jint jheight) { jint* source = env->GetIntArrayElements(buffer, 0); int width = jwidth; int height = jheight; int r, g, b; int count = 0; int bright = 0; count = width * height; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { int localTemp = source[j * width + i]; r = (localTemp >> 16) & 0xff; g = (localTemp >> 8) & 0xff; b = localTemp & 0xff; bright = (int) (bright + 0.299 * r + 0.587 * g + 0.114 * b); } } return bright / count; } 计算亮度对图片要求不高,可以先缩小图片后计算,对亮度计算几乎无影响。 //缩放 public static Bitmap scaleMatrix(Bitmap bitmap, float scaleX, float scaleY){ Log.d(TAG, "scaleMatrix start"); try { int w = bitmap.getWidth(); int h = bitmap.getHeight(); float scaleW = scaleX; float scaleH = scaleY; Matrix matrix = new Matrix(); matrix.postScale(scaleW, scaleH); // 长和宽放大缩小的比例 Bitmap scaleBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, false); Log.d(TAG, "scaleMatrix normal end"); return scaleBitmap; } catch (Exception e) { e.printStackTrace(); } Log.d(TAG, "scaleMatrix error end"); return bitmap; }
android获取图片亮度
猜你喜欢
转载自my.oschina.net/u/1162691/blog/2906879
今日推荐
周排行