1

Estoy intentando subir una imagen a mi servidor que se toma desde la cámara de mi celular, estuve investigando de como hacerlo y encontré que es posible al convertir en base64, la cuestión es que al convertirla en base64 el tamaño de la imagen disminuye drásticamente y no es posible distinguir ni las letras

introducir la descripción de la imagen aquí

para subirla al servidor utilizo el siguiente código:

private String convertImage(Bitmap image) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm = Bitmap
    byte[] b = baos.toByteArray();
    String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);//imagen codificada

    return encodedImage;
}

Despues de codificar la imagen genero un JSON y en el mando la imagen y otra información al servidor por post con retrofit2:

 private void callBack(){
    alertDialogProgress();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ApiInterface.URL_BASE)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    String picture = convertImage(saveImage);
    String descriptionIncidence = textDescription.getText().toString();
    String idEmployee = "1";//Valor obtenido de archivo de preferencias

    ApiInterface apiInterface = retrofit.create(ApiInterface.class);

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("idEmployee", idEmployee);
        jsonObject.put("descriptionIncidence", descriptionIncidence);
        jsonObject.put("picture", picture);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    String json = jsonObject.toString();

    Call<DoneObject> userCall = apiInterface.createIncidence(json);
    userCall.enqueue(new Callback<DoneObject>() {
        @Override
        public void onResponse(Call<DoneObject> call, Response<DoneObject> response) {
            if (response.isSuccessful()) {
                DoneObject doneObject = response.body();
                Toast.makeText(NewIncidenceActivity.this, doneObject.getDone(), Toast.LENGTH_LONG).show();
                alertProgress.dismiss();
                finish();
            }
        }
        @Override
        public void onFailure(Call<DoneObject> call, Throwable t) {
            Log.e("ret2", t.getMessage());
            Toast.makeText(NewIncidenceActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
            alertProgress.dismiss();
        }
    });
}

En mi servidor obtengo los datos, la imagen la decodifico y la guardo en un directorio.

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// header("Content-Type: text/html;charset=utf-8");
require 'mysql_connect.php';

$parametro = $_POST["json"];
$json = json_decode($parametro, true);

$picture = $json["picture"];
$descriptionIncidence = $json["descriptionIncidence"];
$idEmployee = $json["idEmployee"];

$date = date("Ymd");
$time = date("His");

$namePicture = 'img_'.$date.'_'.$time.'_'.$idEmployee.'.jpg';
$dirPicture = '../img-incidence/'.$namePicture;

$urlPicture = 'http://localhost/img-incidence/'.$namePicture;
// $urlPicture = 'http://localhost/pp/img-incidences/'.$namePicture;

$imgdecode = base64_decode($picture);
file_put_contents($dirPicture, $imgdecode );

$connection = mysqli_connect($hostname, $username, $password, $database);
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}
else{
    $query = "INSERT INTO incidencia (FECHA, HORA, DESCRIPCION, IMAGEN, EMPLEADO) 
    VALUES ('$date', '$time', '$descriptionIncidence', '$urlPicture', '$idEmployee')";

    if ($connection->query($query) === TRUE) {
        print (json_encode(
            array(
                'done' => 'done'
            )
            ));
    } else {
        print (json_encode(
            array(
                'done' => $connection->error
            )
            ));
    } 
    mysqli_close($connection);  
}

} ?>

Agradezco cualquier tipo de ayuda o consejo

1 respuesta 1

0

Pues no creo que sea del todo el problema con Base64. Lo digo porque estoy haciendo una aplicación parecida usando imágenes de Galería y/o Cámara. Pero el problema que indicas me pasa solo cuando uso cámara porque si uso galería esta se convierte en Base64 pero llega al servidor con full calidad.
Así se ve desde app: Así se ve desde app Y así es el resultado: Resultado

3
  • Si, es mi problema, cuando llegan al servidor llegan de un tamaño similar a la foto que subiste, he buscado desde ya hace unos días y no encuentro solución
    – Alberto zt
    el 17 feb. 2019 a las 16:38
  • @Albertozt Revisa esto es.stackoverflow.com/questions/158478/…
    – lxndr-rl
    el 18 feb. 2019 a las 18:49
  • Asi es esa fue la solución, gracias por el aporte de la pregunta Qwerty Uiop
    – Alberto zt
    el 26 feb. 2019 a las 5:08

Tu Respuesta

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

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.