Color类
#ifndef COLORGETTER_H_
#define COLORGETTER_H_
class Color {
public:
Color(int color):
color(color)
{};
int alpha() { return (color & 0xFF000000) >> 24; }
int R() { return (color & 0x00FF0000) >> 16; };
int G() { return (color & 0X0000FF00) >> 8; }
int B() { return (color & 0x000000FF); }
int grayScale() {
return (R() + G() + B()) / 3;
}
private:
int color;
};
static inline int ARGB2Color(int alpha, int r, int g, int b) {
return alpha << 24 | r << 16 | g << 8 | b;
}
static inline int RGB2Color(int r, int g, int b) {
return 255 << 24 | r << 16 | g << 8 | b;
}
#endif
工具方法
static inline void changeImageToGray(int* pixels, int width, int height) {
for (int i = 0; i < width * height; i++) {
Color color(pixels[i]);
float gray = color.R() * 0.3 + color.G() * 0.59 + color.B() * 0.11;
pixels[i] = RGB2Color(gray, gray, gray);
}
}
JNI函数
/**
* 获取sketch(轮廓)
*/
void sketchFilter(int *pixels, int width, int height) {
changeImageToGray(pixels, width, height);
int *tempPixels = new int[width * height];
memcpy(tempPixels, pixels, width * height * sizeof(int));
int threshold = 7;
float num = 8;
for (int i = 1; i < height - 1; i++) {
for (int j = 1; j < width - 1; j++) {
//tempPixels[i][j]
Color centerColor(tempPixels[i * width + j]);
int centerGray = centerColor.R();
////tempPixels[i+1][j+1]
Color rightBottomColor(tempPixels[(i + 1) * width + j + 1]);
int rightBottomGray = rightBottomColor.R();
if (abs(centerGray - rightBottomGray) >= threshold) {
//数值超过threshold,则赋值为黑色
pixels[i * width + j] = RGB2Color(0, 0, 0);
} else {
//否则为白色
pixels[i * width + j] = RGB2Color(255, 255, 255);
}
}
}
delete [] tempPixels;
}
#endif
android调用
public static Bitmap createSketch(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);
Bitmap returnBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
int[] returnPixels = sketchFilter(pixels, width, height);
returnBitmap.setPixels(returnPixels, 0, width, 0, 0, width, height);
return returnBitmap;
}
public static native int[] sketchFilter(int[] pixels, int width, int height);