1

tengo una aplicación en desarrollo en donde subo una imagen a un servidor externo.

Mi problema es: si el usuario tiene un celular con cámara de buena resolución, las imágenes tienen un tamaño grande... y no se muestran en el ImageView, así como tampoco se suben al servidor por el peso en MB que tienen.

He investigado algunos ejemplos y he encontrado que se utiliza algo como lo siguiente:

Para reescalar la imagen:

Bitmap yourBitmap;
Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);

Para comprimir la imagen:

Bitmap bmp = BitmapFactory.decodeFile(miFoto)
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 70, bos);
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody foto = new InputStreamBody(in, "image/jpeg", "filename");

Pero no se como utilizar este código para adaptarlo a mi código. Ó en que parte de mi código va.

Este es mi código para obtener las imágenes:

private void showOptions(){
        final CharSequence[] option = {"Tomar foto", "Elegir de galeria", "Cancelar"};
        final AlertDialog.Builder builder = new AlertDialog.Builder(Modificar.this);
        builder.setTitle("Elige una opción");
        builder.setItems(option, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                if(option[which] == "Tomar foto"){
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                        //Verifica permisos para Android 6.0+
                        checkExternalStoragePermission();
                    }

                    File file = new File(Environment.getExternalStorageDirectory(), MEDIA_DIRECTORY);
                    boolean isDirectoryCreated = file.exists();

                    if(!isDirectoryCreated)
                        isDirectoryCreated = file.mkdirs();

                    if(isDirectoryCreated){
                        Long timestamp = System.currentTimeMillis() / 1000;
                        imageName = timestamp.toString() + ".jpg";
                        mPath = Environment.getExternalStorageDirectory() + File.separator + MEDIA_DIRECTORY
                                + File.separator + imageName;
                        newFile = new File(mPath);
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(newFile));
                        startActivityForResult(intent, PHOTO_CODE);
                    }



                } else if(option[which] == "Elegir de galeria"){
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    try {
                        startActivityForResult(Intent.createChooser(intent, "Selecciones un administrador de archivos"),SELECT_PICTURE);
                    }catch (android.content.ActivityNotFoundException ex){

                    }



                }else {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode){
            case SELECT_PICTURE:
                if (resultCode == RESULT_OK){
                    subir.setEnabled(true);
                    Bitmap photobmp;
                    Uri selectedImageUri = data.getData();
                    String dataFU = getRealPathFromURI(selectedImageUri);
                    newFile = new File(dataFU);
                    photobmp = BitmapFactory.decodeFile(dataFU);
                    imagen.setImageBitmap(photobmp);
                    imageName = dataFU.substring(dataFU.lastIndexOf("/")+1);
                    nombreImagen.setText(imageName);
                    break;
                }
            case PHOTO_CODE:
                if(resultCode == RESULT_OK) {
                    MediaScannerConnection.scanFile(this,
                            new String[]{mPath}, null,
                            new MediaScannerConnection.OnScanCompletedListener() {
                                @Override
                                public void onScanCompleted(String path, Uri uri) {
                                    Log.i("ExternalStorage", "Scanned " + path + ":");
                                    Log.i("ExternalStorage", "-> Uri = " + uri);
                                }
                            });
                    Bitmap bitmap = BitmapFactory.decodeFile(mPath);
                    imagen.setImageBitmap(bitmap);
                    nombreImagen.setText(imageName);
                    subir.setEnabled(true);
                    break;
                }
        }
    }

Espero me puedan apoyar!

1
  • ya pudiste, para que también publiques la respuesta, tengo la misma duda. el 12 sep. 2017 a las 22:08

0

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies