Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing an ImageView to black and white NOT the drawable

Tags:

android

I would like to change an imageview to black and white, not the drawable. The reason for this is because the user takes a photo and it gets displayed in the imageview If you know how to do this, id appreciate it, thanks.

package com.example.triptych4;

import java.io.File;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {


    // label our logs "CameraApp3"
    private static String logtag = "CameraApp3";
    // tells us which camera to take a picture from
    private static int TAKE_PICTURE = 1;
    // empty variable to hold our image Uri once we store it
    private Uri imageUri;

    private Integer[] pics = { R.drawable.android, R.drawable.android3d,
          R.drawable.background3 };

    {

    ImageView imageView = (ImageView)findViewById(R.id.imageView1);

    ColorMatrix matrix = new ColorMatrix();
    matrix.setSaturation(0);

    ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
    imageView.setColorFilter(filter);

    }

    private ImageView imageView;


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

        Gallery gallery = (Gallery) findViewById(R.id.gallery1);
        gallery.setAdapter(new ImageAdapter(this));
        imageView = (ImageView) findViewById(R.id.imageView1);

        gallery.setOnItemClickListener( new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
                    long arg3) {
                Toast.makeText(getApplicationContext(), "pic:" + arg2, 
                        Toast.LENGTH_SHORT).show();
                imageView.setImageResource(pics[arg2]);

            }
        });


        // look for the button we set in the view
        ImageButton cameraButton = (ImageButton)
                findViewById(R.id.button_camera);
        // set a listener on the button
        cameraButton.setOnClickListener(cameraListener);

    }




    // set a new listener
    private OnClickListener cameraListener = new OnClickListener() {
        public void onClick(View v) {
            // open the camera and pass in the current view
            takePhoto(v);
        }
    };

    public void takePhoto(View v) {
        // tell the phone we want to use the camera
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // create a new temp file called pic.jpg in the "pictures" storage area of the phone
        File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "pic.jpg");
        // take the return data and store it in the temp file "pic.jpg"
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
        // stor the temp photo uri so we can find it later
        imageUri = Uri.fromFile(photo);
        // start the camera
        startActivityForResult(intent, TAKE_PICTURE);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public class ImageAdapter extends BaseAdapter{
        private Context context;
        int imageBackground;

        public ImageAdapter(Context context){
            this.context = context;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return pics.length;
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            // TODO Auto-generated method stub
            ImageView imageView =new ImageView(context);
            imageView.setImageResource(pics[arg0]);
            return imageView;
        }
    } 
    // override the original activity result function
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // call the parent
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode) {
        // if the requestCode was equal to our camera code (1) then...
        case 1:
            // if the user took a photo and selected the photo to use
            if(resultCode == Activity.RESULT_OK) {
                // get the image uri from earlier
                Uri selectedImage = imageUri;
                // notify any apps of any changes we make
                getContentResolver().notifyChange(selectedImage, null);
                // get the imageView we set in our view earlier
                ImageButton imageButton = (ImageButton)findViewById(R.id.button_camera);
                // create a content resolver object which will allow us to access the image file at the uri above
                ContentResolver cr = getContentResolver();
                // create an empty bitmap object
                Bitmap bitmap;
                try {
                    // get the bitmap from the image uri using the content resolver api to get the image
                    bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
                    // set the bitmap to the image view
                    imageButton.setImageBitmap(bitmap);
                    // notify the user
                    Toast.makeText(MainActivity.this, selectedImage.toString(), Toast.LENGTH_LONG).show();
                } catch(Exception e) {
                    // notify the user
                    Toast.makeText(MainActivity.this, "failed to load", Toast.LENGTH_LONG).show();
                    Log.e(logtag, e.toString());
                }
            }   
        }   
    }     
}

Logcat:

05-22 10:26:07.156: D/AndroidRuntime(24617): Shutting down VM
05-22 10:26:07.156: W/dalvikvm(24617): threadid=1: thread exiting with uncaught exception (group=0x41cac700)
05-22 10:26:07.156: E/AndroidRuntime(24617): FATAL EXCEPTION: main
05-22 10:26:07.156: E/AndroidRuntime(24617): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.triptych4/com.example.triptych4.MainActivity}: java.lang.NullPointerException
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2219)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.app.ActivityThread.access$700(ActivityThread.java:159)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.os.Looper.loop(Looper.java:137)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.app.ActivityThread.main(ActivityThread.java:5419)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at java.lang.reflect.Method.invokeNative(Native Method)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at java.lang.reflect.Method.invoke(Method.java:525)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at dalvik.system.NativeStart.main(Native Method)
05-22 10:26:07.156: E/AndroidRuntime(24617): Caused by: java.lang.NullPointerException
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.app.Activity.findViewById(Activity.java:1914)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at com.example.triptych4.MainActivity.<init>(MainActivity.java:47)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at java.lang.Class.newInstanceImpl(Native Method)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at java.lang.Class.newInstance(Class.java:1130)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2210)
05-22 10:26:07.156: E/AndroidRuntime(24617):    ... 11 more
like image 318
Harrison Avatar asked Feb 11 '23 01:02

Harrison


1 Answers

You can use a ColorMatrix and set the saturation to zero thereby turning your image into black and white. You then use that ColorMatrix as a filter for your imageView.

ImageView imageView = (ImageView)findViewById(R.id.imageView);
...

ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);

ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
imageView.setColorFilter(filter);
like image 194
Christian Abella Avatar answered Feb 15 '23 09:02

Christian Abella