Android:将imageview转换为位图,转换为灰度,将位图转换为imageview

时间:2013-11-29 04:49:28

标签: android bitmap grayscale

编译此代码时,我不会在eclipse上收到任何警告,但是当我在设备或模拟器上运行时,该程序被强制关闭。

public class MainActivity extends Activity {

    ImageView img;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //convert imageview to bitmap
        img =(ImageView) findViewById(R.id.imageView1);
        BitmapDrawable drawable = (BitmapDrawable) img.getDrawable();
        final Bitmap imgbitmap = drawable.getBitmap();


        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //convert bitmap to grayscale 
                Bitmap imgnew;
                imgnew = toGrayscale(imgbitmap);    

                //convert bitmap to imageview 
                ImageView imgbit;
                imgbit = (ImageView) findViewById(R.id.imageView2);
                imgbit.setImageBitmap(imgnew);
            }
        });

    }

    public Bitmap toGrayscale(Bitmap bmpOriginal){        
        int width, height;
        height = bmpOriginal.getHeight();
        width = bmpOriginal.getWidth();    

        Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas c = new Canvas(bmpGrayscale);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bmpOriginal, 0, 0, paint);
        return bmpGrayscale;
    }

}

1 个答案:

答案 0 :(得分:1)

如果以上是您的完整代码,那么基本问题就在那里,您还没有定义btn。您需要在使用它之前定义它,否则当您自动点击按钮时它将无法工作。这可能会关闭你的申请。

 btn=(Button) findViewById(R.id.button1);