3

soy aprendiz y estoy chequeando un error en una app.

En un formulario se intenta cargar una imagen desde la galería o cámara. Si la imagen que se está cargando tiene un peso mayor a 8MB (aproximadamente), no se carga la imagen al servidor. La carga se realiza a través de PHP.

Si, yo intento cargar imagenes de menor peso, si funciona bien. No hay problema con esto.

Creacion de la imagen

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir("Pictures");
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = "file:" + image.getAbsolutePath();
        return image;
    }

    public void camara(View v) throws IOException {


        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
                Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_SHORT).show();
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                imageUri = FileProvider.getUriForFile(public_reg2.this,
                        BuildConfig.APPLICATION_ID,
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(takePictureIntent, 0);
            }
        }
        dialog.dismiss();

    }
    private Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    // Return image / video
    private File getOutputMediaFile(int type) {

        // External sdcard location
        File mediaStorageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == 1) { // image
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
        } else if (type == 2) { // video
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }
    public void galeria(View view) {

        Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
        startActivityForResult(gallery, 1);
        dialog.dismiss();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if(resultCode == RESULT_OK){
            switch(requestCode) {
                case 0:
                    iv6.setImageURI(imageUri);



// For further image Upload i suppose your method for image upload is UploadImage

                    break;
                case 1:
                    try {
                        // Get uri
                        imageUri = data.getData();

                        bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
                        int nh = (int) (bitmap.getHeight() * (1024.0 / bitmap.getWidth()));
                        Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 1024, nh, true);
                        // Set image
                        iv6.setImageBitmap(scaled);
                        iv6.setVisibility(View.VISIBLE);
                        a = 1;
                    } catch (Exception e) {
                        Toast.makeText(this, "Error el obtener la imagen", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }

                    break;

            }
        }
    }

Carga de la imagen

 public String getPathFromURI(Uri contentUri)
    {
        try
        {
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        catch (Exception e)
        {
            return contentUri.getPath();
        }
    }
    public static Bitmap decodeSampledBitmapFromFile(String imagePath,
                                                     int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        //return Bitmap.createScaledBitmap(bt, reqWidth, reqHeight, false);
        return BitmapFactory.decodeFile(imagePath, options);
    }

    public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }



public void subir(View v){
    ImageUploadToServerFunction();

}
public byte[] getBytes(InputStream inputStream) throws IOException {
    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];

    int len = 0;
    while ((len = inputStream.read(buffer)) != -1) {
        byteBuffer.write(buffer, 0, len);
    }
    return byteBuffer.toByteArray();
}
public void ImageUploadToServerFunction(){


    InputStream iStream = null;
    try {
        iStream = getContentResolver().openInputStream(uri);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    byte[] byteArrayVar = new byte[0];
    try {
        byteArrayVar = getBytes(iStream);
    } catch (IOException e) {
        e.printStackTrace();
    }

    final String ConvertImage = Base64.encodeToString(byteArrayVar, Base64.DEFAULT);

    class AsyncTaskUploadClass extends AsyncTask<Void,Void,String> {

        @Override
        protected void onPreExecute() {

            super.onPreExecute();


            alertadd.show();
            //progressDialog = ProgressDialog.show(public_reg3.this,"Cargando datos...","Por favor, espere...",false,false);
        }

Configuracion en PHP

$ImageData = $_POST['image_path'];
$dir_subida = '../img/';
$dir_img = 'https://sitioweb.com/admin/img/';

$extensiones = array('jpg', 'jpeg', 'gif', 'png', 'bmp');

//Obtenemos la extensión (en minúsculas) para poder comparar

$extension = "png";

$nombre_img = $usuario .".". $extension;

$fichero_subido = $dir_subida . $nombre_img;

$dir_img = 'https://sitioweb.com/admin/img/' . $nombre_img;

//Verificamos que sea una extensión permitida, si no lo es mostramos un mensaje de error
if(!in_array($extension, $extensiones)) {
    die( 'Sólo se permiten archivos con las siguientes extensiones: '.implode(', ', $extensiones) );

Por otra parte, creo que es importante darles a conocer que es necesario hacer una conversión a las imagenes cargadas al servidor. Agradecida

4
  • 1
    En tu AsyncTask no se muestra que realiza para subir la imagen, solo muestras el método onPreExecute()
    – Jorgesys
    el 29 sep. 2021 a las 21:00
  • Actualice, la publicacion. Cargué mas detalles.
    – Lilibeth
    el 29 sep. 2021 a las 21:21
  • 1
    Revisa esta pregunta.
    – Sal
    el 30 sep. 2021 a las 0:15
  • en vez de tratar de mandar todo como una cadena que además almacenarías en memoria, intenta mandar por pedazos o chunks usando tu stream como en esta respuesta stackoverflow.com/a/39099064/6999690 el 22 nov. a las 13:35

0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Examina otras preguntas con la etiqueta o formula tu propia pregunta.