Estoy haciendo un app en Android
que envía una imagen al servidor. La imagen es sacada de la galería. El problema es que la imagen que tomo desde la cámara está en vertical y al verla en el servidor se pone en modo horizontal. Creo que el problema es del web service que está hecho en php
.
Por eso, quisiera saber si hay manera de rotar la imagen que es leída con:
$image = base64_decode($image);
y lo guarda con
file_put_contents($path, $image);
Este es el codigo completo del php
<?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);
}
?>
Este es el codigo en 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,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();
}
}
}
}
}
pd: soy la misma persona (Jair Vasquez)