Skip to content

Instantly share code, notes, and snippets.

@amadeu01
Last active January 22, 2018 14:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amadeu01/02d6c53f4b0d07c7b1b29b6d996a9442 to your computer and use it in GitHub Desktop.
Save amadeu01/02d6c53f4b0d07c7b1b29b6d996a9442 to your computer and use it in GitHub Desktop.
Helper for handling bitmap on Android
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.ExifInterface;
import android.util.Base64;
public class ScalingUtilities {
public static String encodeInBase64(String imageFilePath) {
String imageBase64Encoded = "";
try {
InputStream imageInputStream = new FileInputStream(imageFilePath);
ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream();
IOUtils.copy(imageInputStream, imageOutputStream);
imageInputStream.close();
imageBase64Encoded = Base64.encodeToString(imageOutputStream.toByteArray(), Base64.NO_WRAP);
imageOutputStream.close();
} catch (IOException e) {
App.logException(e);
} finally {
File photoFile = new File(imageFilePath);
if (photoFile.exists())
photoFile.delete();
}
return imageBase64Encoded;
}
private int getExifOrientation(String filePath) {
ExifInterface exif = null;
try {
exif = new ExifInterface(filePath);
} catch (IOException ignore) {
}
return exif == null ? ExifInterface.ORIENTATION_UNDEFINED :
exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
}
private Bitmap rotateBitmap(Bitmap bitmap, int orientation) {
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
return bitmap;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
matrix.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(-90);
break;
default:
return bitmap;
}
try {
Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return bmRotated;
} catch (OutOfMemoryError ignore) {
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment