how do I rotate an image in php?

1

I'm doing an android app that sends me a form together with an image to the server but the images come out horizontal. That is, I'm going to the server and I see that the image is saved but horizontally

This is the android code

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.kosalgeek.android.photoutil.CameraPhoto;
import com.kosalgeek.android.photoutil.GalleryPhoto;
import com.kosalgeek.android.photoutil.ImageBase64;
import com.kosalgeek.android.photoutil.ImageLoader;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.EachExceptionsHandler;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.proyectojs.blackmate.user.User;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.HashMap;

import cz.msebera.android.httpclient.Header;
import android.Manifest;

import static android.R.attr.data;


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,ivImage;
Spinner spinnerDistrito,spinnerInteres;
CameraPhoto cameraPhoto;
GalleryPhoto galleryPhoto;

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

String selectedPhoto="";

String idProveedor;
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(Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.CAMERA},1);
            }
        }

        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,new String[] {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);
        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"};

    String[] intereses = {"Diversión","Diversión y apoyo económico","Relación abierta"};

    spinnerDistrito.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, distritos));
    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();
                                //bitmap=redimensionarImagenMaximo(bitmap,512,512);


                                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);
                                            idProveedor = jsonObject.getString("id");
                                            msg = jsonObject.getString("msg");
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                        if(msg.equals("uploaded_success")){
                                            mDatabase.child("Proveedores").child("P"+idProveedor).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();
                                        }
                                    }
                                });
                                task.execute("http://blackmate.esy.es/blackmateapp/insertarProveedor.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();
            }
        }
    }
}

}

I think the problem is with my php (web service)

This is the 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 proveedor 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 proveedor WHERE Nick='$nick'";
$result2 = mysql_query($consultaNick);
while ($fila2 = mysql_fetch_array($result2)) {
if($nick == $fila2['Nick']){
    $mensaje="nick_existe";
}
}

if($mensaje=="registro_insertado"){

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

mysql_query($consulta);

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

$image = base64_decode($image);


if(file_put_contents($path,$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);

}

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

?>
    
asked by Jave 28.02.2017 в 17:31
source

0 answers