Do not save the photo on the server with the selfie camera

1

I'm doing an app in android on a form that saves an image ... there is a button that redirects you to the gallery to put it as a profile photo ... the images that have been saved with the front camera if you save it on the server ... but I have tried with pictures of the selfie camera and it does not save anything or register the form in the database.

code on android

public class Register extends AppCompatActivity{

private final String TAG =this.getClass().getName();

Button btnreg;
Button btncancel;
EditText edUser,edPassword,edPassword2,edNick,edEmail,edEdad,edDescripcion;
ImageView ivCamera,ivGallery,ivUpload,ivImage;
Spinner spinnerDistrito,spinnerInteres;
CameraPhoto cameraPhoto;
GalleryPhoto galleryPhoto;

final int CAMERA_REQUEST=13323;
final int GALLERY_REQUEST=22131;

String selectedPhoto="";

String idCliente;
String msg;

DatabaseReference mDatabase= FirebaseDatabase.getInstance().getReference();

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register2);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            if(checkSelfPermission(android.Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,new String[] {android.Manifest.permission.CAMERA},1);
            }
        }

        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            if(checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,new String[] {android.Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
            }
        }

        cameraPhoto=new CameraPhoto(getApplicationContext());
        galleryPhoto=new GalleryPhoto(getApplicationContext());

        //ivCamera=(ImageView)findViewById(R.id.ivCamera);
        ivGallery=(ImageView)findViewById(R.id.ivGallery);
        //ivUpload=(ImageView)findViewById(R.id.ivGallery);
        ivImage=(ImageView)findViewById(R.id.ivimage);
        btncancel=(Button)findViewById(R.id.btnCancelar2);
        btnreg=(Button)findViewById(R.id.btnRegister2);
        edUser=(EditText)findViewById(R.id.et_user2);
        edPassword=(EditText)findViewById(R.id.et_password);
        edPassword2=(EditText)findViewById(R.id.et_password2);
        edNick=(EditText)findViewById(R.id.et_nick2);
        edEmail=(EditText)findViewById(R.id.et_email2);
        edEdad=(EditText)findViewById(R.id.et_edad2);
        edDescripcion=(EditText)findViewById(R.id.et_descripcion);

        spinnerInteres=(Spinner) findViewById(R.id.spinner_Interes);
        spinnerDistrito=(Spinner)findViewById(R.id.spinnerDistrito2);

    String[] distritos = {"Ancón","Ate","Barranco","Breña","Carabayllo","Chaclacayo", "Chorrillos", "Cieneguilla"
            , "Comas", "El Agustino", "Independencia (Lima)", "Jesús María", "La Molina", "La Victoria", "Lima", "Lince",
            "Los Olivos", "Lurigancho-Chosica", "Lurín", "Magdalena del Mar", "Miraflores", "Pachacámac",
            "Pucusana", "Pueblo Libre", "Puente Piedra", "Punta Hermosa", "Punta Negra", "Rímac", "San Bartolo", "San Borja",
            "San Isidro", "San Juan de Lurigancho", "San Juan de Miraflores", "San Luis", "San Martín de Porres", "San Miguel",
            "Santa Anita", "Santa María del Mar", "Santa Rosa (Lima)", "Santiago de Surco", "Villa El Salvador", "Villa María del Triunfo"};
    spinnerDistrito.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, distritos));

    String[] intereses = {"Diversión","Diversión y apoyo económico","Relación abierta"};
    spinnerInteres.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,intereses));
        /*ivCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    startActivityForResult(cameraPhoto.takePhotoIntent(),CAMERA_REQUEST);
                    cameraPhoto.addToGallery();
                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(),"Something Wrong while taking photos",Toast.LENGTH_SHORT).show();
                }
            }
        });*/

        ivGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    startActivityForResult(galleryPhoto.openGalleryIntent(),GALLERY_REQUEST);
            }
        });


    btnreg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                     String edad=edEdad.getText().toString();
                     final String user=edUser.getText().toString();
                     String pass=edPassword.getText().toString();
                     String pass2=edPassword2.getText().toString();
                     String nick=edNick.getText().toString();
                     final String email=edEmail.getText().toString();
                     String descripcion=edDescripcion.getText().toString();
                     String interes=spinnerInteres.getSelectedItem().toString();
                     String distrito=spinnerDistrito.getSelectedItem().toString();

                    if(!user.equals("") && !pass.equals("") && !pass2.equals("") && !nick.equals("") && !email.equals("") && !edad.equals("") && !descripcion.equals("") && !interes.equals("")){
                        if(pass.equals(pass2)){
                            if(!selectedPhoto.equals("") || selectedPhoto!=null){
                                Bitmap bitmap=ImageLoader.init().from(selectedPhoto).getBitmap();

                                String encodedImage= ImageBase64.encode(bitmap);
                                //Log.d(TAG,encodedImage);

                                HashMap<String,String> postData=new HashMap<String, String>();

                                postData.put("image",encodedImage);
                                postData.put("user",user);
                                postData.put("password",pass);
                                postData.put("nick",nick);
                                postData.put("email",email);
                                postData.put("edad",edad);
                                postData.put("distrito",distrito);
                                postData.put("descripcion",descripcion);
                                postData.put("interes",interes);

                                PostResponseAsyncTask task=new PostResponseAsyncTask(Register.this, postData, new AsyncResponse() {

                                    @Override
                                    public void processFinish(String s) {
                                        Log.d("JSON",s);
                                        try {
                                            JSONObject jsonObject=new JSONObject(s);
                                            idCliente = jsonObject.getString("id");
                                            msg = jsonObject.getString("msg");
                                        } catch (JSONException e) {
                                            msg = e.toString();
                                        }
                                       Log.d("msg",msg);
                                        if(msg.equals("uploaded_success")){
                                            mDatabase.child("Clientes").child("C"+idCliente).setValue(new User(user,email));
                                            Toast.makeText(getApplicationContext(),"Member registrado exitosamente",Toast.LENGTH_LONG).show();
                                            Intent intent=new Intent(getApplicationContext(),Login.class);
                                            startActivity(intent);
                                        }else if(msg.equals("user_existe")){
                                            Toast.makeText(getApplicationContext(),"El Usuario ya existe",Toast.LENGTH_LONG).show();
                                        }else if(msg.equals("nick_existe")){
                                            Toast.makeText(getApplicationContext(),"El Nick ya existe",Toast.LENGTH_LONG).show();
                                        }else if(msg.equals("uploaded_failed")){
                                            Toast.makeText(getApplicationContext(),"Cannot Connect to Server.",Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                                task.execute("http://blackmate.esy.es/blackmateapp/insertarCliente.php");
                                task.setEachExceptionsHandler(new EachExceptionsHandler() {
                                    @Override
                                    public void handleIOException(IOException e) {
                                        Toast.makeText(getApplicationContext(),"Cannot Connect to Server.",Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void handleMalformedURLException(MalformedURLException e) {
                                        Toast.makeText(getApplicationContext(),"URL Error.",Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void handleProtocolException(ProtocolException e) {
                                        Toast.makeText(getApplicationContext(),"Protocol Error.",Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void handleUnsupportedEncodingException(UnsupportedEncodingException e) {
                                        Toast.makeText(getApplicationContext(),"Encoding Error.",Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }else{
                                Toast.makeText(getApplicationContext(),"No haz seleccionado imagen",Toast.LENGTH_LONG).show();
                            }
                        }else{
                            Toast.makeText(getApplicationContext(),"Las Contraseñas no coinciden",Toast.LENGTH_LONG).show();
                        }
                    }else{
                        Toast.makeText(getApplicationContext(),"Faltan datos por completar",Toast.LENGTH_LONG).show();
                    }
                } catch (FileNotFoundException e) {
                    Toast.makeText(getApplicationContext(),"No haz seleccionado imagen",Toast.LENGTH_SHORT).show();
                }
            }
        });


        btncancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i=new Intent(getApplicationContext(),Login.class);
                startActivity(i);
            }
        });



}

public Bitmap redimensionarImagenMaximo(Bitmap mBitmap, float newWidth, float newHeigth){
    //Redimensionamos
    int width = mBitmap.getWidth();
    int height = mBitmap.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeigth) / height;
    // create a matrix for the manipulation
    Matrix matrix = new Matrix();
    // resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);
    // recreate the new Bitmap
    return Bitmap.createBitmap(mBitmap, 0, 0, width, height, matrix, false);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode==RESULT_OK){
        if(requestCode==CAMERA_REQUEST){
            String photoPath= cameraPhoto.getPhotoPath();
            selectedPhoto=photoPath;
            Bitmap bitmap;
            try {
                bitmap= ImageLoader.init().from(photoPath).requestSize(512,512).getBitmap();

                File imageFile = new File(photoPath);
                ExifInterface exif = null;
                try {
                    exif = new ExifInterface(imageFile.getAbsolutePath());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                int rotate = 360;
                switch (orientation) {
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        rotate = 270;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        rotate = 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        rotate = 90;
                        break;
                }


                Matrix matrix = new Matrix();
                matrix.postRotate(rotate);
                Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap,512,512,true);
                Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap , 0, 0, scaledBitmap .getWidth(), scaledBitmap .getHeight(), matrix, true);

                ivImage.setImageBitmap(rotatedBitmap);
            } catch (FileNotFoundException e) {
                Toast.makeText(getApplicationContext(),"Something Wrong while loading photos",Toast.LENGTH_SHORT).show();
            }
            Log.d(TAG,photoPath);
        }else if(requestCode==GALLERY_REQUEST){
                Uri uri=data.getData();
                galleryPhoto.setPhotoUri(uri);
                String photoPath=galleryPhoto.getPath();
                selectedPhoto=photoPath;
            Bitmap bitmap;
            try {
                bitmap= ImageLoader.init().from(photoPath).requestSize(512,512).getBitmap();

                File imageFile = new File(photoPath);
                ExifInterface exif = null;
                try {
                    exif = new ExifInterface(imageFile.getAbsolutePath());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                int rotate = 360;
                switch (orientation) {
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        rotate = 270;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        rotate = 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        rotate = 90;
                        break;
                }


                Matrix matrix = new Matrix();
                matrix.postRotate(rotate);
                Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap,512,512,true);
                Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap , 0, 0, scaledBitmap .getWidth(), scaledBitmap .getHeight(), matrix, true);


                ivImage.setImageBitmap(rotatedBitmap);
            } catch (FileNotFoundException e) {
                Toast.makeText(getApplicationContext(),"Something Wrong while choosing photos",Toast.LENGTH_SHORT).show();
            }
        }
    }
}
}

php code

 <?php

 require("conexion.php");

 $image =$_REQUEST['image'];
 $user = $_REQUEST['user'];
 $password = $_REQUEST['password'];
 $nick = $_REQUEST['nick'];
 $email = $_REQUEST['email'];
 $edad = $_REQUEST['edad'];
 $distrito =$_REQUEST['distrito'];
 $descripcion =$_REQUEST['descripcion'];
 $interes =$_REQUEST['interes'];

 $now=DateTime::createFromFormat('U.u',microtime(true));
 $id=$now->format('YmdHisu');

 $foto1 = "$id.jpg";

 $mensaje="registro_insertado";

 //verificando si existe usuario
 $consultaUser = "SELECT * FROM cliente WHERE User='$user'";
 $result = mysql_query($consultaUser);
 while ($fila = mysql_fetch_array($result)) {
  if($user == $fila['User']){
    $mensaje="user_existe";
 }
 }

 //verificando si existe nick
 $consultaNick = "SELECT * FROM cliente WHERE Nick='$nick'";
 $result2 = mysql_query($consultaNick);
 while ($fila2 = mysql_fetch_array($result2)) {
  if($nick == $fila2['Nick']){
    $mensaje="nick_existe";
 }
 }


 if($mensaje=="registro_insertado"){

if($user!="" && $nick!=""){

$consulta = "INSERT INTO cliente (User,Password,Nick,Email,Distritos,Edad,Foto1,Descripcion,Intereses) VALUES ('$user','$password','$nick','$email','$distrito','$edad','$foto1','$descripcion','$interes')";

mysql_query($consulta);

$path="../imagenesCliente/$id.jpg";

/*if(file_put_contents($path,base64_decode($image)) != false){

    $id = mysql_insert_id();
    $msg = "uploaded_success";
    $arr = array('msg' => $msg , 'id' => $id);
    echo json_encode($arr);

}else{

    $msg = "uploaded_failed";
    $arr = array('msg' => $msg , 'id' => "");
    echo json_encode($arr);

}*/

    $data = base64_decode($image); // base64 decoded image data

    $source_img = imagecreatefromstring($data);

    $rotated_img = imagerotate($source_img, 270, 0); // rotate with angle 90 here

    $imageSave = imagejpeg($rotated_img, $path, 75);

    imagedestroy($source_img);

    $id = mysql_insert_id();

    $msg = "uploaded_success";

    $arr = array('msg' => $msg , 'id' => $id);

    echo json_encode($arr);



}else{
    $msg = "uploaded_failed";

    $arr = array('msg' => $msg , 'id' => "");

    echo json_encode($arr);
}

 }else{
$arr = array('msg' => $mensaje , 'id' => "");
echo json_encode($arr);
 }

 ?>
    
asked by Jave 08.03.2017 в 21:38
source

0 answers