改变图片灰度
/**
* 色彩图转换成黑白图
*/
public static Bitmap convertGreyImage(Bitmap bitmap) {
//获取位图的宽
int width = bitmap.getWidth();
//获取位图的高
int height = bitmap.getHeight();
//创建像素点数组
int[] piexls = new int[width * height];
bitmap.getPixels(piexls, 0, width, 0, 0, width, height);
int alpha = 0xFF << 24;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int grey = piexls[width * i + j];
int red = ((grey & 0x00FF0000) >> 16);
int green = ((grey & 0x0000FF00) >> 8);
int blue = (grey & 0x000000FF);
grey = (int) ((float) red * 0.3 + (float) green * 0.59 + (float) blue * 0.11);
grey = alpha | (grey << 16) | (grey << 8) | grey;
piexls[width * i + j] = grey;
}
}
//创建Bitmap
Bitmap newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
newBitmap.setPixels(piexls, 0, width, 0, 0, width, height);
return newBitmap;
}
压缩图片
/**
* 压缩处理Bitmap图片
*/
public static Bitmap compressImage(Bitmap bitmap) {
ByteArrayOutputStream bao = new ByteArrayOutputStream();
/**
* 压缩Bitmap到字节数组输出流, 100表示不压缩,0表示压缩最小
* 把压缩的数据送到bao
*/
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bao);
int options = 100;
//循环判断如果压缩后图片是否大于100kb,大于继续压缩
while (bao.toByteArray().length / 1024 > 100) {
//清空bao
bao.reset();
bitmap.compress(Bitmap.CompressFormat.JPEG, options, bao);
options -= 10;
}
//取出数据
ByteArrayInputStream bai = new ByteArrayInputStream(bao.toByteArray());
//生成图片
Bitmap newBitmap = BitmapFactory.decodeStream(bai, null, null);
return newBitmap;
}