Skip to content

Instantly share code, notes, and snippets.

@dwirandyh
Created December 16, 2019 06:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwirandyh/e884ba797aec81baa916d8b2ac989fe8 to your computer and use it in GitHub Desktop.
Save dwirandyh/e884ba797aec81baa916d8b2ac989fe8 to your computer and use it in GitHub Desktop.
Upload Image From Gallery
/**
* Interface for uploading image
*
* @param photo
* @param name
* @param email
* @param phoneNumber
* @param about
* @return
*/
@POST("auth/me/update")
@Multipart
fun updateProfile(
@Part photo: MultipartBody.Part?,
@Part("name") name: RequestBody?,
@Part("email") email: RequestBody?,
@Part("phoneNumber") phoneNumber: RequestBody?,
@Part("about") about: RequestBody?
): Single<ActionResponse>
/**
* Method to open browse dialog
*
*/
fun onClickBrowseImage() {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
val mimeTypes = arrayOf("image/jpeg", "image/png")
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
startActivityForResult(intent, GALLERY_REQUEST_CODE)
}
/**
* Get result from gallery
*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// respond pick gallery result
if (requestCode == GALLERY_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
data?.let {
it.data?.let { uri ->
try {
selectedProfileBitmap = decodeUri(this, uri, 512)
Glide.with(this)
.asBitmap()
.load(uri)
.into(binding.imageProfile)
} catch (e: Exception) {
Toast.makeText(
this,
"There is something worng, try again later",
Toast.LENGTH_SHORT
).show()
}
}
}
}
}
}
/**
* Resize bitmap from uri that is got from storage
*
* @param context
* @param uri
* @param requiredSize
* @return
*/
@Throws(FileNotFoundException::class)
fun decodeUri(context: Context, uri: Uri, requiredSize: Int): Bitmap? {
val bitmapOption = BitmapFactory.Options()
bitmapOption.inJustDecodeBounds = true
BitmapFactory.decodeStream(
context.contentResolver.openInputStream(uri),
null,
bitmapOption
)
var widthTmp = bitmapOption.outWidth
var heightTmp = bitmapOption.outHeight
var scale = 1
while (true) {
if (widthTmp / 2 < requiredSize || heightTmp / 2 < requiredSize) break
widthTmp /= 2
heightTmp /= 2
scale *= 2
}
val o2 = BitmapFactory.Options()
o2.inSampleSize = scale
return BitmapFactory.decodeStream(
context.contentResolver.openInputStream(uri),
null,
o2
)
}
/**
* Create temporary file for bitmap
*
* @param bitmap
* @return
*/
private fun createTempFile(bitmap: Bitmap): File? {
val file = File(
getExternalFilesDir(Environment.DIRECTORY_PICTURES)
, System.currentTimeMillis().toString() + "_image.jpg"
)
val bos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos)
val bitmapData: ByteArray = bos.toByteArray()
//write the bytes in file
try {
val fos = FileOutputStream(file)
fos.write(bitmapData)
fos.flush()
fos.close()
} catch (e: IOException) {
e.printStackTrace()
}
return file
}
/**
* Get real path from uri for uploading image
*
* @param contentUri
* @return
*/
fun getRealPathFromURI(contentUri: Uri?): String? {
var path: String? = null
val proj = arrayOf(MediaStore.MediaColumns.DATA)
val cursor: Cursor? = contentResolver.query(contentUri!!, proj, null, null, null)
cursor?.let {
if (cursor.moveToFirst()) {
val column_index: Int = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
path = cursor.getString(column_index)
}
cursor.close()
return path
}
return null
}
/**
* Do upload
*/
fun onClickEdit() {
if (editProfileViewObservable.isValid()) {
var photoPart: MultipartBody.Part? = null
selectedProfileBitmap?.let {
val photoRequestBody = createTempFile(it)?.asRequestBody()
photoRequestBody?.let {
photoPart = MultipartBody.Part.createFormData(
"photo",
"${userProfile?.id}-photo-profile.jpg",
photoRequestBody
)
}
}
viewModel.updateProfile(
photoPart,
editProfileViewObservable.getName()?.toRequestBody(),
editProfileViewObservable.getEmail()?.toRequestBody(),
editProfileViewObservable.getPhoneNumber()?.toRequestBody(),
editProfileViewObservable.getAbout()?.toRequestBody()
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment