1.ColorMatrix 矩阵运算
色彩:针对每个像素做处理
/**
* ColorMatrix 操作像素
* @param src
* @return
*/
public static Bitmap gray(Bitmap src) {
Bitmap dst = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
Canvas canvas = new Canvas(dst);
Paint paint = new Paint();
paint.setDither(true);
paint.setAntiAlias(true);
// final float R = 0.213f * invSat;
// final float G = 0.715f * invSat;
// final float B = 0.072f * invSat;
// 4 * 5 的矩阵 同setSaturation同样效果
// ColorMatrix colorMatrix = new ColorMatrix(new float[]{
// 0.213f, 0.715f,0.072f, 0, 0,
// 0.213f, 0.715f,0.072f, 0, 0,
// 0.213f, 0.715f,0.072f, 0, 0,
// 0, 0, 0, 1, 0
// });
//原图效果
// ColorMatrix colorMatrix = new ColorMatrix(new float[]{
// 1, 0, 0, 0, 0,
// 0, 1, 0, 0, 0,
// 0, 0, 1, 0, 0,
// 0, 0, 0, 1, 0
// });
//底片效果
ColorMatrix colorMatrix = new ColorMatrix(new float[]{
-1, 0, 0, 0, 255,
0, -1, 0, 0, 255,
0, 0, -1, 0, 255,
0, 0, 0, 1, 0
});
// 灰度效果
// colorMatrix.setSaturation(0);
ColorMatrixColorFilter colorMatrixColorFilter = new ColorMatrixColorFilter(colorMatrix);
paint.setColorFilter(colorMatrixColorFilter);
canvas.drawBitmap(src, 0, 0, paint);
return dst;
}
2.Bitmap 获取像素操作
/**
* Bitmap操作像素
* @param src
* @return
*/
public static Bitmap gray2(Bitmap src) {
Bitmap dst = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
int[] pixels = new int[src.getWidth() * src.getHeight()];
src.getPixels(pixels, 0, src.getWidth(), 0, 0, src.getWidth(), src.getHeight());
for (int i = 0; i < pixels.length; i++) {
int p = pixels[i];
int a = (p >> 24) & 0xff;
int r = (p >> 16) & 0xff;
int g = (p >> 8) & 0xff;
int b = p & 0xff;
int gray = (int) (0.213f * r + 0.715f * g + 0.072f * b);
pixels[i] = a << 24 | gray << 16 | gray << 8 | gray;
}
dst.setPixels(pixels, 0, src.getWidth(), 0, 0, src.getWidth(), src.getHeight());
return dst;
}
3.Native 层操作像素指针
#include <jni.h>
#include <string>
#include <android/bitmap.h>
extern "C"
JNIEXPORT void JNICALL
Java_com_example_myapplication_BitmapUtils_gray3(JNIEnv *env, jclass clazz, jobject bitmap) {
AndroidBitmapInfo bitmapInfo;
int result = AndroidBitmap_getInfo(env, bitmap, &bitmapInfo);
if (result != 0) {
return;
}
void *pixels;
AndroidBitmap_lockPixels(env, bitmap, &pixels);
for (int i = 0; i < bitmapInfo.width * bitmapInfo.height; ++i) {
uint32_t *pixel_p = reinterpret_cast<uint32_t *>(pixels) + i;
uint32_t p = *pixel_p;
int a = (p >> 24) & 0xff;
int r = (p >> 16) & 0xff;
int g = (p >> 8) & 0xff;
int b = p & 0xff;
int gray = (int) (0.213f * r + 0.715f * g + 0.072f * b);
*pixel_p = a << 24 | gray << 16 | gray << 8 | gray;
}
AndroidBitmap_unlockPixels(env, bitmap);
}
使用的时候可能报错
image.png
需要在CMakeLists.txt 文件中target_link_libraries下添加jnigraphics
例如
image.png
4.ARGB_8888 和 RGB_565
ARGB_8888 的大小是RGB_565的两倍
RGB_565 没有alpha通道rgb各占5、6、5位一个色素占两字节
ARGB_8888 一个色素占四字节