Josef
Josef

Reputation: 452

Get the content of image view in android

In my app the user can laod an image from Gallery or from Camera and it be shown in

imageView. What i want to do is to send the image to my server. In order to that,

i should to convert it to Base64 type.

Everything is well but i don't know how to get the content of the imageView for converting it,

and where exactly to put the code.

My activity is :

public class MainActivity extends Activity {    
    private static int FROM_CAMERA = 1;
    private static int FROM_GALLERY = 2;

    ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    EditText inputName;
    EditText inputEmail;
    Button sendData;
    JSONObject json;
    ImageView userImg;


    private static String url_create_user = "http://localhost/android_connect/create_user.php";


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


        inputName = (EditText)findViewById(R.id.userName);
        inputEmail = (EditText)findViewById(R.id.email);
        sendData = (Button)findViewById(R.id.send);
        userImg = (ImageView)findViewById(R.id.userImage);


        sendData.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (isNetworkConnected())
                    new CreateNewUser().execute();
                else
                    Toast.makeText(getApplicationContext(), "Please connect to internet!", Toast.LENGTH_LONG).show();

            }
        });


        userImg.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String[] options = new String[]{"Camera","Gallery"};
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

                builder.setItems(options, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if(which == 0){
                            Intent c = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(c, FROM_CAMERA);
                        }
                        else{
                            Intent g = new Intent(Intent.ACTION_GET_CONTENT);
                            g.setType("image/*");
                            startActivityForResult(g, FROM_GALLERY);

                        }
                    }
                });

                builder.create();
                builder.show(); 
            }

        });



    }   



    class CreateNewUser extends AsyncTask<String, String,String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Creating user...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }   


        @Override
        protected String doInBackground(String... arg0) {
            String username = inputName.getText().toString();
            String email = inputEmail.getText().toString();


            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("email", email));

            json = jsonParser.makeHttpRequest(url_create_user, "POST", params);

            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {


                } else {

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }





        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
            if(json != null){
                Toast.makeText(getApplicationContext(), "The data has been sent successfully!", Toast.LENGTH_LONG).show();
            }
            else
                Toast.makeText(getApplicationContext(), "Failed to send data!", Toast.LENGTH_LONG).show();


        }


    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ImageView imageView = (ImageView)findViewById(R.id.userImage);

        if (requestCode == FROM_GALLERY && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);

            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        }
        else{
            if(requestCode == FROM_CAMERA  && resultCode == RESULT_OK && null != data )
            {

                Bundle extras = data.getExtras();
                Bitmap photo = extras.getParcelable("data");
                imageView.setImageBitmap(photo);


            }
        }




    }



    private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni == null) return false;
        else return true;   
    }

}

This is the code for convert the image to base64:

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); 
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);

and i should add this sentence in doInBackground method:

params.add(new BasicNameValuePair("image", image_str));

Thanks!!!

Upvotes: 1

Views: 3087

Answers (2)

Josef
Josef

Reputation: 452

I solved my problem. here is the solution:

To get the content of the image to bitmap i do this -

Bitmap bitmap = ((BitmapDrawable)userImg.getBackground()).getBitmap();

and this works very well without any errors.

I put the converting code in onActivityResult() like this:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FROM_GALLERY && resultCode == RESULT_OK && null != data) {

    //Getting the image from gallery and set it to imageView

}
else{
    if(requestCode == FROM_CAMERA  && resultCode == RESULT_OK && null != data )
    {

        //Getting the image from camera and set it to imageView

    }
}

Bitmap bitmap = ((BitmapDrawable)userImg.getBackground()).getBitmap();

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); 
byte [] byte_arr = stream.toByteArray();
image = Base64.encodeToString(byte_arr, Base64.DEFAULT);

}

Everything get well.

Upvotes: 1

kelvincer
kelvincer

Reputation: 6138

This is how you get the bitmap of your Imageview:

Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

After you convert to base64.

Upvotes: 1

Related Questions