简体   繁体   中英

Android : Converting imageview to bitmap, to grayscale, bitmap to imageview

I don't don't get any warning on eclipse when I compile this code, but when I run it on device or emulator, that program was forced to close.

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;
    }

}

If above is your full code then, basic problem is there, you haven't define btn . You need to define it before using it, else when you ar egoing to click on the button it will not work. and this might closing your application.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM