Hola.
La imagen que subo pesa 514kb y otra 1500 kb, son imágenes sacadas con la cámara del móvil. Aunque podría darse el caso de que alguien subiera una bastante pesada y seria conveniente ver como poder quitarle calidad.
El tema de guardarlo en SD p en una bd sqlite no me sirve puesto que esta imagen será el avatar del usuario y si este usuario se registra en otro movil ya no tendria el avatar. Por eso lo subo a un servidor.
Lo que hago es seleccionar una imagen de la galería o tomar una foto y mostrarla en un ImageButton. Al registrarse subo mediante ftp la imagen a un servidor.
En el momento de logearse obtengo esa ruta y a partir de ella creo un bitMap el que comprimo y paso a Base 64 para guardarlo en SharedPreferences.
Una vez logeado recupero esa SharedPreferences y muestro el bitMap en un ImageButton.
El codigo de lo descrito anteriormente es el siguiente:
ACTIVITY REGISTRO
Selecciono o tomo una foto:private void dialogPhoto() {
try {
final CharSequence[] items = { "Seleccionar de la galería",
"Hacer una foto" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Seleccionar una foto");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, SELECT_IMAGE);
break;
case 1:
startActivityForResult(
new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE),
TAKE_PICTURE);
break;
}
}
});
AlertDialog alert = builder.create();
alert.show();
} catch (Exception e) {
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImage = null;
try {
if (requestCode == SELECT_IMAGE)
if (resultCode == Activity.RESULT_OK) {
selectedImage = data.getData();
ruta = getPath(selectedImage);
int tamRuta = ruta.length();
int posBarra = ruta.lastIndexOf("/");
name = ruta.substring(posBarra+1);
setPic(btnAvatar,ruta);
f = new File(ruta,name);
}
if (requestCode == TAKE_PICTURE)
if (resultCode == Activity.RESULT_OK) {
selectedImage = data.getData();
}
} catch (Exception e) {
}
}
private String getPath(Uri uri) {
String[] projection = { android.provider.MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(android.provider.MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Muestro la imagen seleccionada en el ImageButton:
private void setPic(ImageButton mImageView, String imageURI) {
// Get the original bitmap dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imageURI, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, REQ_HEIGHT, REQ_WIDTH);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(imageURI, options);
//need rotation?
float rotation = rotationForImage(this, Uri.fromFile(new File(imageURI)));
if (rotation != 0) {
//rotate
Matrix matrix = new Matrix();
matrix.preRotate(rotation);
mImageView.setImageBitmap(Bitmap.createBitmap(bitmap, 180,100, REQ_HEIGHT, REQ_WIDTH, matrix, true));
// REQ_HEIGHT = 450, REQ_WIDTH = 450 } else {
//use the original
mImageView.setImageBitmap(BitmapFactory.decodeFile(imageURI, options));
}
SharedPreferences prefs = getSharedPreferences("MisPreferencias",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putFloat(TAG_URIAVATAR, rotation);
editor.commit();
}
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) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
public static float rotationForImage(Context context, Uri uri) {
try {
if (uri.getScheme().equals("content")) {
String[] projection = { Images.ImageColumns.ORIENTATION };
Cursor c = context.getContentResolver().query(uri, projection, null, null, null);
if (c.moveToFirst()) {
return c.getInt(0);
}
} else if (uri.getScheme().equals("file")) {
ExifInterface exif = new ExifInterface(uri.getPath());
int rotation = (int) exifOrientationToDegrees(exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL));
return rotation;
}
return 0;
} catch (IOException e) {
Log.e("ERROR", "Error checking exif", e);
return 0;
}
}
private static float exifOrientationToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
return 90;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
return 180;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
return 270;
}
return 0;
}
Subo mediante ftp la imagen al servidor: try{
FTPClient ftpClient = new FTPClient();
ftpClient.connect(InetAddress.getByName(servidor));
ftpClient.login(TAG_USERFTP, TAG_PASSFTP);
ftpClient.changeWorkingDirectory(TAG_URLIMAGEN);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
BufferedInputStream buffIn=null;
buffIn=new BufferedInputStream(new FileInputStream(ruta));
ftpClient.enterLocalPassiveMode();
ftpClient.storeFile(name, buffIn);
buffIn.close();
ftpClient.logout();
ftpClient.disconnect();
avatarSubido = "Ok";
urlAvatar = name;
}catch (Exception e) {
Log.d("ERROR FTP: ", e.getMessage().toString());
}
ACTIVITY LOGEOCreo un bitMap a partir de la ruta obtenida, lo comprimo, convierto a Base64 y guardo en SharedPreferences
URL url = new URL(urlAvatarl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 20, baos);
// AQUI COMPRIMO LA IMAGEN SI NO ME EQUIVOCO
byte[] b = baos.toByteArray();
encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
// TODO Auto-generated method stub
SharedPreferences prefs = getSharedPreferences("MisPreferencias",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(TAG_URLAVATAR, encodedImage);
editor.commit();
ACTIVITY TRAS LOGEARSE
Recupero SharedPreferences y que viene en Base64, creo el bitMap y lo muestro en un ImageButton urlAvatar = prefs.getString(TAG_URLAVATAR, "");
rotation = prefs.getFloat(TAG_URIAVATAR, 0);
setPic(btnPerfil,urlAvatar);
private void setPic(ImageButton mImageView, String imageURI) {
// Get the original bitmap dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
byte[] b = Base64.decode(urlAvatar, Base64.DEFAULT);
BitmapFactory.decodeByteArray(b, 0, b.length, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, REQ_HEIGHT, REQ_WIDTH);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeByteArray(b, 0, b.length, options);
//need rotation?
// float rotation = rotationForImage(getApplicationContext(), Uri.fromFile(new File(uriAvatar)));
if (rotation != 0) {
//rotate
Matrix matrix = new Matrix();
matrix.preRotate(rotation);
mImageView.setImageBitmap(Bitmap.createBitmap(bmp, 180, 100, REQ_HEIGHT, REQ_WIDTH, matrix, true));
} else {
//use the original
mImageView.setImageBitmap(BitmapFactory.decodeByteArray(b, 0, b.length, 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) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
public static float rotationForImage(Context context, Uri uri) {
try {
if (uri.getScheme().equals("content")) {
String[] projection = { Images.ImageColumns.ORIENTATION };
Cursor c = context.getContentResolver().query(uri, projection, null, null, null);
if (c.moveToFirst()) {
return c.getInt(0);
}
} else if (uri.getScheme().equals("file")) {
ExifInterface exif = new ExifInterface(uri.getPath());
int rotation = (int) exifOrientationToDegrees(exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL));
return rotation;
}
return 0;
} catch (IOException e) {
Log.e("ERROR", "Error checking exif", e);
return 0;
}
}
private static float exifOrientationToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
return 90;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
return 180;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
return 270;
}
return 0;
}
mucho de este código a sido obtenido de otras fuentes para remediar problemas que me fueron surgiendo. Puede que hayas numerosas chapuzas o barbaridades que puedan ser mejoradas, pero por mi inexperiencia y mi poco conocimiento no se si es así por lo que estoy abierto a cualquier cambio que pueda arreglar o mejorar cosas y de este modo también me serviría para aprender. Gracias