import image from gallery - android

Asked

Viewed 657 times

0

Eai personal, I need help with my application, I have q select an image from the gallery, make it appear in an imageView and save it in the database(sqlite), so q the person can exit the application and keep the photo for when return, this already helps a lot and if it is possible to make the application take a photo with a decent quality and also show in the image view and save in the bank

1 answer

1


The following is an example of what you need: 1) Shows on the screen option of choice: selects gallery photo or photo taking; 2) Shows in imageview; 3) Upload to a web api, I use for Asp.net mvc but can be used for other languages as well;

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btnChooseImage:
            final CharSequence[] items = { "Take Photo", "Choose from Library",
                    "Cancel" };
            AlertDialog.Builder builder = new AlertDialog.Builder(UploadDocumentsActivity.this);
            builder.setTitle("Add Photo!");
            builder.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {
                    boolean result= UtilityPermission.checkPermission(UploadDocumentsActivity.this);
                    if (items[item].equals("Take Photo")) {
                        userChoosenTask="Take Photo";
                        if(result)
                            cameraIntent();
                    } else if (items[item].equals("Choose from Library")) {
                        userChoosenTask="Choose from Library";
                        if(result)
                            galleryIntent();
                    } else if (items[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
            break;
        case R.id.btnUploadImage:
            uploadImage();
            break;

    }
}

private void galleryIntent()
{
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);//
    startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}

private void cameraIntent()
{
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, REQUEST_CAMERA);
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_FILE) {
            if (data != null) {
                try { bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        else if (requestCode == REQUEST_CAMERA) {
            bitmap = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
            File destination = new File(Environment.getExternalStorageDirectory(),
                    System.currentTimeMillis() + ".jpg");
            FileOutputStream fo;
            try {
                destination.createNewFile();
                fo = new FileOutputStream(destination);
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        imgForUpload.setImageBitmap(bitmap);
    }
}

private void uploadImage(){
    class UploadImage extends AsyncTask<Bitmap,Void,String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            hideProgressDialog();
            Toast.makeText(getApplicationContext(),s, Toast.LENGTH_LONG).show();
            if (response.length() == 0)
            {
                resultRequest = false;
                errorMessage  = "Image has uploaded successfull";
                ShowAlert();
                if (lastActivity.equals("Profile")) {
                    Intent i = new Intent(UploadDocumentsActivity.this, MenuPageActivity.class);
                    obj.setLastActivity("UploadDocuments");
                    startActivity(i);
                }
                else
                {
                    Intent i = new Intent(UploadDocumentsActivity.this, VehicleActivity.class);
                    startActivity(i);
                }
            }
            else
            {
                resultRequest = false;
                errorMessage  = "Server is not responding or internet is not working, try later";
                ShowAlert();
            }
        }

        @Override
        protected String doInBackground(Bitmap... params) {
            obj  = (AppController) getApplicationContext();
            String url = "http://server/xx";
            String final_upload_filename = "demo_image.png";
            HttpURLConnection conn = null;
            try {
                String lineEnd = "\r\n";
                String twoHyphens = "--";
                String boundary = "---------------------------14737809831466499882746641449";
                URL urlDestiny = new URL(url);
                conn = (HttpURLConnection) urlDestiny.openConnection();
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/octet-stream");
                conn.setRequestProperty("Authorization", "Bearer " + obj.getToken());
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"" + param + "\"; filename=\"" + 
                                final_upload_filename + "\"" + lineEnd);
                dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
                dos.writeBytes(lineEnd);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, dos);
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                dos.flush();
                dos.close();
                InputStream is = conn.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int bytesRead;
                byte[] bytes = new byte[1024];
                while ((bytesRead = is.read(bytes)) != -1) {
                    baos.write(bytes, 0, bytesRead);
                }
                byte[] bytesReceived = baos.toByteArray();
                baos.close();
                is.close();
                response = new String(bytesReceived);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
            return response;
        }
    }
    UploadImage ui = new UploadImage();
    ui.execute(bitmap);
}
  • had already seen a similar code, if I am not mistaken this missing a java file with permissions, it would be good a layout xml, and I did not understand part 3 upload in a web api, I just wanted to save even q were the way in the database , you don’t know any simple way to do that ?

  • I do not know the simplest option, this is the one I use and works very well. Yes, the permissions is mandatory requirement in newer versions of android, I wiped the code to stay only what you asked for. Option 3 (web api) is the server to which the image will be forwarded to be saved to the server on the server, that is, in a folder where the server is hosted and also the address of this path (link) is recorded in the database so that in the future, when the user enters this record both by mobile and by a web application he can see the image that was recorded.

  • my need is to register only in the local bank (Sqlite) is unnecessary this option in my application, but anyway thanks for the help

  • Blz...so this last part is simpler. As I have not yet done local recording I have no way to help you...if the above section helps you, give us a Up ai...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.