BitMap 学习

来源:互联网 发布:java源代码实例 编辑:程序博客网 时间:2024/05/29 10:14

BitMap是什么

BitMap代表一张图片


常用操作

获取像素点的颜色值 getPixel

设置像素点的颜色值 setPixel

压缩图片 compress


使用实例

1.截取图片,重命名后保存

String path  = /sdcard/图片名;

File storePath = new File("path");

UiDevice.getInstance().takeScreenshot(imagePath);//截取图片

sleep(3000);

Bitmap bitmap = BitmapFactory.decodeFile(path);//创建bitmap

saveBitMapToSdcard(bitmap,"newImage");

public void saveBitMapToSdcard(Bitmap bitmap,String name)

{

FileOutputStream out = null;

try{

out = new FileOutputStream(/sdcard/+"name"+".jpg");

if(null!=out)

{

bitmap.compress(Bitmap.CompressFormat.JPEG,90,out);

out.close();

}

    }catch(Exception e)

{

}

}

2.获取某个坐标点的颜色值

publicint getColorPicel(int x,int y){

String path="/mnt/sdcard/testcolor.png";

File file=new File(path);

UiDevice.getInstance().takeScreenshot(file);

Bitmap m=BitmapFactory.decodeFile(path);

int color=m.getPixel(x, y);

return color;

}

     3.在图片上加文字(使用Canvas画上去)

publicvoid screenshotAndDrawText(String path,String imageName,String text){

File file=new File(path);

UiDevice.getInstance().takeScreenshot(file);

Bitmap bitmap=BitmapFactory.decodeFile(path);

Bitmap drawBitmap=drawTextBitmap(bitmap, text);

saveBitMapToSdcard(drawBitmap, imageName);

}

public Bitmap drawTextBitmap(Bitmap bitmap,String text){

int x=bitmap.getWidth();

int y=bitmap.getHeight();

//创建一个比原来图片更大的位图

Bitmap newBitmap=Bitmap.createBitmap(x, y+80, Bitmap.Config.ARGB_8888);

Canvas canvans=new Canvas(newBitmap);

Paint paint=new Paint();

//在原图位置(00)叠加一张图片

canvans.drawBitmap(bitmap,0,0, paint);

//画笔颜色

paint.setColor(Color.parseColor("#FF0000"));

paint.setTextSize(30);

canvans.drawText(text,20, y+55, paint);

canvans.save(Canvas.ALL_SAVE_FLAG);//保存canvas状态 入栈

canvans.restore();//恢复canvas的之前的保存状态,防止save后对后续绘制有影响 最后一个状态出栈

return newBitmap;

}

4.图像对比(比如一个按钮按下与弹起各自设置图片,我们通过图片可以判断按钮的状态)

publicboolean imageSameAs(String targetImagePath,String comPath,double percent){

try {

Bitmap m1=BitmapFactory.decodeFile(targetImagePath);

Bitmap m2=BitmapFactory.decodeFile(comPath);

int width=m2.getWidth();

int height=m2.getHeight();

int numDiffPixels=0;

for(int y=0;y<height;y++){

for(int x=0;x<width;x++){

if(m2.getPixel(x, y)!=m1.getPixel(x, y)){

numDiffPixels++;

}

}

}

double totalPicels=height*width; //所有像素

double diffPercent=numDiffPixels/totalPicels; //计算不同的百分比

return percent<=1.0-diffPercent;

}catch (Exception e) {

}

returnfalse;

}


0 0
原创粉丝点击