Skip to content

Instantly share code, notes, and snippets.

@john-lorrenz
Last active November 13, 2019 09:51
Show Gist options
  • Save john-lorrenz/f6b81fa8ba412779888f7f93af70526d to your computer and use it in GitHub Desktop.
Save john-lorrenz/f6b81fa8ba412779888f7f93af70526d to your computer and use it in GitHub Desktop.
Bitmap Manipulation
/*
Sample Parameter:
String: "file:///storage/emulated/0/Android/data/com.example.disappeardents/cache/roof_1.jpg"
*/
fun uriStringToBitmap(uriString : String) : Bitmap {
val uri = uriString.toUri()
val uriPath = uri.path
val bitmap = BitmapFactory.decodeFile(uriPath)
return bitmap
}
/*
Sample Parameter:
1: Bitmap: [bitmap]
2: String: "my_file_name.jpg"
*/
fun bitmapToUriString(bitmap: Bitmap, fileName: String) : Uri{
// set directory where it will be stored (on cache)
var file = File(activity!!.externalCacheDir, fileName)
// save the image on cache
var fOut = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fOut)
// get the path of the image
var uriPath = Uri.fromFile(file)
return uriPath
}
fun rescaleBitmap(uriString : Uri) : Bitmap {
val uriPath = uriString.path
val bitmap = BitmapFactory.decodeFile(uriPath)
val maxSize = 800
println("size: " + bitmap.byteCount)
println("width: " + bitmap.width)
println("height: " + bitmap.height)
var width = bitmap.width
var height = bitmap.height
val bitmapRatio = width / height;
if (bitmapRatio > 1) {
width = maxSize
height = (width / bitmapRatio)
} else {
height = maxSize
width = (height * bitmapRatio)
}
val rescaledBitmap = Bitmap.createScaledBitmap(bitmap, width, height, true)
println("new size: " + rescaledBitmap.byteCount)
println("new width: " + rescaledBitmap.width)
println("new height: " + rescaledBitmap.height)
return rescaledBitmap
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment