最近女朋友在做图片对比的测试用例,我看到了顺手改了一下。
原理就是先将两张图片读取成bitmap,然后对比宽、高,如果相符,最后再对对应的像素点判断是否相同
<span style="white-space:pre"> </span>if (bitmap1.getHeight() != bitmap2.getHeight())
return false;
if (bitmap1.getWidth() != bitmap2.getWidth())
return false;
if (bitmap1.getConfig() != bitmap2.getConfig())
return false;
int width = bitmap1.getWidth();
int height = bitmap2.getHeight();
//记录相异的像素点的数量
int numDiffPixels = 0;
Bitmap diffBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas c = new Canvas(diffBitmap);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bitmap1, 0, 0, paint);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (bitmap1.getPixel(x, y) != bitmap2.getPixel(x, y)) {
diffBitmap.setPixel(x, y, Color.RED);//这里是当判断到该像素点不一致时,将该像素的颜色置为红色
numDiffPixels++;
}
else {
// diffBitmap.setPixel(x, y, bitmap1.getPixel(x, y));
}
}
}
if(bitmap1!=null){
bitmap1.recycle();
bitmap1 = null;
}
if(bitmap2!=null){
bitmap2.recycle();
bitmap2 = null;
}
FileOutputStream fos = null;
try {
File diff_File = new File(DIFF_PATH);
if (diff_File.exists()) {
diff_File.delete();
diff_File.createNewFile();
}
fos = new FileOutputStream(diff_File);
diffBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (fos != null) {
try {
fos.flush();
fos.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (diffBitmap != null) {
diffBitmap.recycle();
diffBitmap = null;
}
}
double numberPixels = height * width;
double diffPercent = numDiffPixels / numberPixels;//计算两张图片之间的差异值
效果如下:
图片1:
图片2:
对比图:
由于是在java层运行的,在对比两张像素较高的图片时会比较慢,可以尝试用jni改写