Last active
August 29, 2015 14:26
-
-
Save just-kip/d0f7eb877ec01bb706d4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun crop(file: String) : String{ | |
var bitmap = decode(file) | |
var h = bitmap.getHeight() | |
var w = bitmap.getWidth() | |
val minSideSize = Math.min(h, w) | |
var x = (w - minSideSize) / 2 | |
var y = (h - minSideSize) / 2 | |
val exif = ExifInterface(file) | |
val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) | |
val matrix = Matrix() | |
when(orientation) { | |
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90f) | |
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180f) | |
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270f) | |
} | |
val scaledBitmap = Bitmap.createBitmap(bitmap, x, y, minSideSize, minSideSize, matrix, true) | |
val compressedFilePath = "${getActivity().getCacheDir()}/Locator_${System.currentTimeMillis()}.png" | |
val compressedFile = File(compressedFilePath) | |
val byteArrayOutputStream = ByteArrayOutputStream() | |
scaledBitmap.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream) | |
val bitmapData = byteArrayOutputStream.toByteArray() | |
val fileOutputStream = FileOutputStream(compressedFile) | |
fileOutputStream.write(bitmapData) | |
fileOutputStream.flush() | |
fileOutputStream.close() | |
bitmap.recycle() | |
scaledBitmap.recycle() | |
return compressedFilePath | |
} | |
fun decode(file: String) : Bitmap { | |
val options = BitmapFactory.Options() | |
options.inJustDecodeBounds = true | |
var fileInputStream = FileInputStream(File(file)) | |
BitmapFactory.decodeStream(fileInputStream, null, options) | |
fileInputStream.close() | |
var scale = 1 | |
val minSide = Math.min(options.outHeight, options.outWidth) | |
val maxSide = Math.max(options.outHeight, options.outWidth) | |
if(minSide > MAX_AVATAR_SIDE_SLIDE || maxSide > MAX_AVATAR_SIDE_SLIDE) { | |
scale = (maxSide / MAX_AVATAR_SIDE_SLIDE) | |
} | |
val newOptions = BitmapFactory.Options() | |
newOptions.inSampleSize = scale + 1 | |
fileInputStream = FileInputStream(File(file)) | |
val decodedBitmap = BitmapFactory.decodeStream(fileInputStream, null, newOptions) | |
fileInputStream.close() | |
return decodedBitmap | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment