import gallery image - android

0

Hey guys, I need help with my application, I have to select an image from the gallery, make it appear in an imageView and save it in the database (SQLite) so that the person can exit the application and keep the picture for when it comes back, it helps a lot and if it is possible to make the application take a picture with a decent quality and also show it in the imageview and save it in the bank

    
asked by anonymous 13.10.2016 / 02:14

1 answer

1

Here's an example of what you need: 1) Display on the choice option screen: select gallery photo or take photo; 2) Show in the imageview; 3) Upload in 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);
}
    
13.10.2016 / 02:54