给出一个PNG资源导入,由RGB转灰度并显示的例子,代码如下:
public class GrayView extends View { private Bitmap bmp; public GrayView(Context context) { super(context); Resources res = getResources(); bmp = BitmapFactory.decodeResource(res, R.drawable.ic_launcher);//将ic_launcher则个资源生成一个bitmap对象 } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub Bitmap output = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Config.ARGB_8888);//定义一个与原始bitmap一样大小的bitmap对象 for(int i = 0; i < bmp.getWidth(); i++){ for(int j = 0; j < bmp.getHeight(); j++){ int color = bmp.getPixel(i, j);//获取某一坐标的像素值 int red = Color.red(color); //解析出R、G、B的值 int green = Color.green(color); int blue = Color.blue(color); int tmp = (red + green + blue)/3; //转换成灰度值 output.setPixel(i, j, Color.rgb(tmp,tmp,tmp)); //给相应坐标的像素点赋值R、G、B } } canvas.drawBitmap(output, 100, 100, null);//将该bitmap绘制在canvas上 } }
时间: 2024-11-10 10:47:03