Merge pull request #5917 from osmandapp/TelegramStaleLocation

Telegram icons stale location
This commit is contained in:
Alexander Sytnyk 2018-08-28 15:40:32 +03:00 committed by GitHub
commit a7ed7cde21
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 197 additions and 25 deletions

View file

@ -273,7 +273,7 @@ class TelegramService : Service(), LocationListener, TelegramIncomingMessagesLis
override fun doInBackground(vararg messages: TdApi.Message): Void? { override fun doInBackground(vararg messages: TdApi.Message): Void? {
for (message in messages) { for (message in messages) {
app.showLocationHelper.addLocationToMap(message) app.showLocationHelper.addOrUpdateLocationOnMap(message)
} }
return null return null
} }

View file

@ -11,6 +11,8 @@ import net.osmand.telegram.helpers.TelegramUiHelper.ListItem
import net.osmand.telegram.utils.AndroidUtils import net.osmand.telegram.utils.AndroidUtils
import org.drinkless.td.libcore.telegram.TdApi import org.drinkless.td.libcore.telegram.TdApi
import java.io.File import java.io.File
import android.net.Uri
import net.osmand.telegram.R
class ShowLocationHelper(private val app: TelegramApplication) { class ShowLocationHelper(private val app: TelegramApplication) {
@ -30,7 +32,7 @@ class ShowLocationHelper(private val app: TelegramApplication) {
} }
} }
fun showLocationOnMap(item: ListItem) { fun showLocationOnMap(item: ListItem, stale: Boolean = false) {
if (item.latLon == null) { if (item.latLon == null) {
return return
} }
@ -41,10 +43,10 @@ class ShowLocationHelper(private val app: TelegramApplication) {
item.getVisibleName(), item.getVisibleName(),
item.getVisibleName(), item.getVisibleName(),
item.chatTitle, item.chatTitle,
Color.RED, Color.WHITE,
ALatLon(item.latLon!!.latitude, item.latLon!!.longitude), ALatLon(item.latLon!!.latitude, item.latLon!!.longitude),
null, null,
generatePhotoParams(item.photoPath) generatePhotoParams(if (stale) item.grayscalePhotoPath else item.photoPath, stale)
) )
} }
} }
@ -53,16 +55,18 @@ class ShowLocationHelper(private val app: TelegramApplication) {
execOsmandApi { execOsmandApi {
val messages = telegramHelper.getMessages() val messages = telegramHelper.getMessages()
for (message in messages) { for (message in messages) {
val date = Math.max(message.date, message.editDate) * 1000L val date = telegramHelper.getLastUpdatedTime(message)
val expired = System.currentTimeMillis() - date > app.settings.locHistoryTime * 1000L val messageShowingTime = System.currentTimeMillis() / 1000 - date
if (expired) { if (messageShowingTime > app.settings.locHistoryTime) {
removeMapPoint(message.chatId, message) removeMapPoint(message.chatId, message)
} else if (app.settings.isShowingChatOnMap(message.chatId)) {
addOrUpdateLocationOnMap(message, true)
} }
} }
} }
} }
fun addLocationToMap(message: TdApi.Message) { fun addOrUpdateLocationOnMap(message: TdApi.Message, update: Boolean = false) {
execOsmandApi { execOsmandApi {
val chatId = message.chatId val chatId = message.chatId
val chatTitle = telegramHelper.getChat(message.chatId)?.title val chatTitle = telegramHelper.getChat(message.chatId)?.title
@ -70,6 +74,8 @@ class ShowLocationHelper(private val app: TelegramApplication) {
if (chatTitle != null && content is TdApi.MessageLocation) { if (chatTitle != null && content is TdApi.MessageLocation) {
var userName = "" var userName = ""
var photoPath: String? = null var photoPath: String? = null
val date = telegramHelper.getLastUpdatedTime(message)
val stale = System.currentTimeMillis() / 1000 - date > app.settings.staleLocTime
val user = telegramHelper.getUser(message.senderUserId) val user = telegramHelper.getUser(message.senderUserId)
if (user != null) { if (user != null) {
userName = "${user.firstName} ${user.lastName}".trim() userName = "${user.firstName} ${user.lastName}".trim()
@ -79,20 +85,34 @@ class ShowLocationHelper(private val app: TelegramApplication) {
if (userName.isEmpty()) { if (userName.isEmpty()) {
userName = user.phoneNumber userName = user.phoneNumber
} }
photoPath = telegramHelper.getUserPhotoPath(user) photoPath = if (stale) {
telegramHelper.getUserGreyPhotoPath(user)
} else {
telegramHelper.getUserPhotoPath(user)
}
} }
if (userName.isEmpty()) { if (userName.isEmpty()) {
userName = message.senderUserId.toString() userName = message.senderUserId.toString()
} }
setupMapLayer() setupMapLayer()
val params = generatePhotoParams(photoPath) val params = generatePhotoParams(photoPath, stale)
osmandAidlHelper.addMapPoint(MAP_LAYER_ID, "${chatId}_${message.senderUserId}", userName, userName, if (update) {
chatTitle, Color.RED, ALatLon(content.location.latitude, content.location.longitude), null, params) osmandAidlHelper.updateMapPoint(MAP_LAYER_ID, "${chatId}_${message.senderUserId}", userName, userName,
chatTitle, Color.WHITE, ALatLon(content.location.latitude, content.location.longitude), null, params)
} else {
osmandAidlHelper.addMapPoint(MAP_LAYER_ID, "${chatId}_${message.senderUserId}", userName, userName,
chatTitle, Color.WHITE, ALatLon(content.location.latitude, content.location.longitude), null, params)
}
} else if (chatTitle != null && content is MessageOsmAndBotLocation && content.isValid()) { } else if (chatTitle != null && content is MessageOsmAndBotLocation && content.isValid()) {
val name = content.name val name = content.name
setupMapLayer() setupMapLayer()
osmandAidlHelper.addMapPoint(MAP_LAYER_ID, "${chatId}_$name", name, name, if (update) {
chatTitle, Color.RED, ALatLon(content.lat, content.lon), null, null) osmandAidlHelper.updateMapPoint(MAP_LAYER_ID, "${chatId}_$name", name, name,
chatTitle, Color.WHITE, ALatLon(content.lat, content.lon), null, null)
} else {
osmandAidlHelper.addMapPoint(MAP_LAYER_ID, "${chatId}_$name", name, name,
chatTitle, Color.WHITE, ALatLon(content.lat, content.lon), null, null)
}
} }
} }
} }
@ -101,7 +121,7 @@ class ShowLocationHelper(private val app: TelegramApplication) {
execOsmandApi { execOsmandApi {
val messages = telegramHelper.getChatMessages(chatId) val messages = telegramHelper.getChatMessages(chatId)
for (message in messages) { for (message in messages) {
addLocationToMap(message) addOrUpdateLocationOnMap(message)
} }
} }
} }
@ -135,11 +155,21 @@ class ShowLocationHelper(private val app: TelegramApplication) {
} }
} }
private fun generatePhotoParams(photoPath: String?): Map<String, String>? { private fun generatePhotoParams(photoPath: String?, stale: Boolean = false): Map<String, String>? {
if (TextUtils.isEmpty(photoPath)) { val photoUri = if (TextUtils.isEmpty(photoPath)) {
return null val resId = if (stale) {
R.drawable.img_user_picture
} else {
R.drawable.img_user_picture_active
}
AndroidUtils.resourceToUri(app, resId)
} else {
AndroidUtils.getUriForFile(app, File(photoPath))
} }
val photoUri = AndroidUtils.getUriForFile(app, File(photoPath)) return generatePhotoParamsFromUri(photoUri)
}
private fun generatePhotoParamsFromUri(photoUri: Uri): Map<String, String>? {
app.grantUriPermission( app.grantUriPermission(
app.settings.appToConnectPackage, app.settings.appToConnectPackage,
photoUri, photoUri,

View file

@ -3,6 +3,7 @@ package net.osmand.telegram.helpers
import android.text.TextUtils import android.text.TextUtils
import net.osmand.PlatformUtil import net.osmand.PlatformUtil
import net.osmand.telegram.helpers.TelegramHelper.TelegramAuthenticationParameterType.* import net.osmand.telegram.helpers.TelegramHelper.TelegramAuthenticationParameterType.*
import net.osmand.telegram.utils.*
import org.drinkless.td.libcore.telegram.Client import org.drinkless.td.libcore.telegram.Client
import org.drinkless.td.libcore.telegram.Client.ResultHandler import org.drinkless.td.libcore.telegram.Client.ResultHandler
import org.drinkless.td.libcore.telegram.TdApi import org.drinkless.td.libcore.telegram.TdApi
@ -320,6 +321,14 @@ class TelegramHelper private constructor() {
} }
} }
fun getUserGreyPhotoPath(user: TdApi.User): String? {
return if (hasGrayscaleUserPhoto(user.id)) {
"$appDir/$GRAYSCALE_PHOTOS_DIR${user.id}$GRAYSCALE_PHOTOS_EXT"
} else {
null
}
}
fun getOsmAndBotDeviceName(message: TdApi.Message): String { fun getOsmAndBotDeviceName(message: TdApi.Message): String {
var deviceName = "" var deviceName = ""
if (message.replyMarkup is TdApi.ReplyMarkupInlineKeyboard) { if (message.replyMarkup is TdApi.ReplyMarkupInlineKeyboard) {
@ -358,6 +367,10 @@ class TelegramHelper private constructor() {
updateLiveMessagesExecutor?.awaitTermination(1, TimeUnit.MINUTES) updateLiveMessagesExecutor?.awaitTermination(1, TimeUnit.MINUTES)
} }
fun hasGrayscaleUserPhoto(userId: Int): Boolean {
return File("$appDir/$GRAYSCALE_PHOTOS_DIR$userId$GRAYSCALE_PHOTOS_EXT").exists()
}
private fun hasLocalUserPhoto(user: TdApi.User): Boolean { private fun hasLocalUserPhoto(user: TdApi.User): Boolean {
val localPhoto = user.profilePhoto?.small?.local val localPhoto = user.profilePhoto?.small?.local
return if (localPhoto != null) { return if (localPhoto != null) {

View file

@ -59,6 +59,7 @@ object TelegramUiHelper {
res.chatWithBot = chatWithBot res.chatWithBot = chatWithBot
if (!chatWithBot) { if (!chatWithBot) {
res.userId = userId res.userId = userId
val user = helper.getUser(userId)
val message = messages.firstOrNull { it.viaBotUserId == 0 } val message = messages.firstOrNull { it.viaBotUserId == 0 }
if (message != null) { if (message != null) {
res.lastUpdated = helper.getLastUpdatedTime(message) res.lastUpdated = helper.getLastUpdatedTime(message)
@ -67,6 +68,9 @@ object TelegramUiHelper {
res.latLon = LatLon(content.location.latitude, content.location.longitude) res.latLon = LatLon(content.location.latitude, content.location.longitude)
} }
} }
if (user != null) {
res.grayscalePhotoPath = helper.getUserGreyPhotoPath(user)
}
} }
} else if (type is TdApi.ChatTypeBasicGroup) { } else if (type is TdApi.ChatTypeBasicGroup) {
res.placeholderId = R.drawable.img_group_picture res.placeholderId = R.drawable.img_group_picture
@ -137,6 +141,7 @@ object TelegramUiHelper {
name = TelegramUiHelper.getUserName(user) name = TelegramUiHelper.getUserName(user)
latLon = LatLon(content.location.latitude, content.location.longitude) latLon = LatLon(content.location.latitude, content.location.longitude)
photoPath = helper.getUserPhotoPath(user) photoPath = helper.getUserPhotoPath(user)
grayscalePhotoPath = helper.getUserGreyPhotoPath(user)
placeholderId = R.drawable.img_user_picture placeholderId = R.drawable.img_user_picture
userId = message.senderUserId userId = message.senderUserId
lastUpdated = helper.getLastUpdatedTime(message) lastUpdated = helper.getLastUpdatedTime(message)
@ -153,6 +158,8 @@ object TelegramUiHelper {
internal set internal set
var photoPath: String? = null var photoPath: String? = null
internal set internal set
var grayscalePhotoPath: String? = null
internal set
var placeholderId: Int = 0 var placeholderId: Int = 0
internal set internal set
var userId: Int = 0 var userId: Int = 0

View file

@ -311,7 +311,13 @@ class LiveNowTabFragment : Fragment(), TelegramListener, TelegramIncomingMessage
val canBeOpenedOnMap = item.canBeOpenedOnMap() val canBeOpenedOnMap = item.canBeOpenedOnMap()
val openOnMapView = holder.getOpenOnMapClickView() val openOnMapView = holder.getOpenOnMapClickView()
TelegramUiHelper.setupPhoto(app, holder.icon, item.photoPath, item.placeholderId, false) val staleLocation = System.currentTimeMillis() / 1000 - item.lastUpdated > settings.staleLocTime
if (staleLocation) {
TelegramUiHelper.setupPhoto(app, holder.icon, item.grayscalePhotoPath, item.placeholderId, false)
} else {
TelegramUiHelper.setupPhoto(app, holder.icon, item.photoPath, R.drawable.img_user_picture_active, false)
}
holder.title?.text = item.getVisibleName() holder.title?.text = item.getVisibleName()
openOnMapView?.isEnabled = canBeOpenedOnMap openOnMapView?.isEnabled = canBeOpenedOnMap
if (canBeOpenedOnMap) { if (canBeOpenedOnMap) {
@ -319,7 +325,7 @@ class LiveNowTabFragment : Fragment(), TelegramListener, TelegramIncomingMessage
if (!isOsmAndInstalled()) { if (!isOsmAndInstalled()) {
showOsmAndMissingDialog() showOsmAndMissingDialog()
} else { } else {
app.showLocationHelper.showLocationOnMap(item) app.showLocationHelper.showLocationOnMap(item, staleLocation)
} }
} }
} else { } else {
@ -327,7 +333,7 @@ class LiveNowTabFragment : Fragment(), TelegramListener, TelegramIncomingMessage
} }
if (location != null && item.latLon != null) { if (location != null && item.latLon != null) {
holder.locationViewContainer?.visibility = if (item.lastUpdated > 0) View.VISIBLE else View.GONE holder.locationViewContainer?.visibility = if (item.lastUpdated > 0) View.VISIBLE else View.GONE
locationViewCache.outdatedLocation = System.currentTimeMillis() / 1000 - item.lastUpdated > settings.staleLocTime locationViewCache.outdatedLocation = staleLocation
app.uiUtils.updateLocationView( app.uiUtils.updateLocationView(
holder.directionIcon, holder.directionIcon,
holder.distanceText, holder.distanceText,

View file

@ -25,6 +25,8 @@ import net.osmand.telegram.ui.LoginDialogFragment.LoginDialogType
import net.osmand.telegram.ui.MyLocationTabFragment.ActionButtonsListener import net.osmand.telegram.ui.MyLocationTabFragment.ActionButtonsListener
import net.osmand.telegram.ui.views.LockableViewPager import net.osmand.telegram.ui.views.LockableViewPager
import net.osmand.telegram.utils.AndroidUtils import net.osmand.telegram.utils.AndroidUtils
import net.osmand.telegram.utils.GRAYSCALE_PHOTOS_DIR
import net.osmand.telegram.utils.GRAYSCALE_PHOTOS_EXT
import org.drinkless.td.libcore.telegram.TdApi import org.drinkless.td.libcore.telegram.TdApi
import java.lang.ref.WeakReference import java.lang.ref.WeakReference
@ -33,7 +35,7 @@ private const val PERMISSION_REQUEST_LOCATION = 1
private const val MY_LOCATION_TAB_POS = 0 private const val MY_LOCATION_TAB_POS = 0
private const val LIVE_NOW_TAB_POS = 1 private const val LIVE_NOW_TAB_POS = 1
class MainActivity : AppCompatActivity(), TelegramListener, ActionButtonsListener { class MainActivity : AppCompatActivity(), TelegramListener, ActionButtonsListener, TelegramIncomingMessagesListener {
private val log = PlatformUtil.getLog(TelegramHelper::class.java) private val log = PlatformUtil.getLog(TelegramHelper::class.java)
@ -150,6 +152,7 @@ class MainActivity : AppCompatActivity(), TelegramListener, ActionButtonsListene
if (telegramHelper.listener != this) { if (telegramHelper.listener != this) {
telegramHelper.listener = this telegramHelper.listener = this
} }
telegramHelper.addIncomingMessagesListener(this)
app.locationProvider.checkIfLastKnownLocationIsValid() app.locationProvider.checkIfLastKnownLocationIsValid()
@ -164,6 +167,7 @@ class MainActivity : AppCompatActivity(), TelegramListener, ActionButtonsListene
override fun onPause() { override fun onPause() {
super.onPause() super.onPause()
telegramHelper.listener = null telegramHelper.listener = null
telegramHelper.removeIncomingMessagesListener(this)
app.locationProvider.pauseAllUpdates() app.locationProvider.pauseAllUpdates()
@ -219,21 +223,29 @@ class MainActivity : AppCompatActivity(), TelegramListener, ActionButtonsListene
} }
override fun onTelegramChatsChanged() { override fun onTelegramChatsChanged() {
telegramHelper.getMessagesByChatIds(settings.locHistoryTime).forEach {
addGrayPhoto(it.key)
}
runOnUi { runOnUi {
listeners.forEach { it.get()?.onTelegramChatsChanged() } listeners.forEach { it.get()?.onTelegramChatsChanged() }
} }
} }
override fun onTelegramChatChanged(chat: TdApi.Chat) { override fun onTelegramChatChanged(chat: TdApi.Chat) {
addGrayPhoto(chat.id)
runOnUi { runOnUi {
listeners.forEach { it.get()?.onTelegramChatChanged(chat) } listeners.forEach { it.get()?.onTelegramChatChanged(chat) }
} }
} }
override fun onTelegramUserChanged(user: TdApi.User) { override fun onTelegramUserChanged(user: TdApi.User) {
val photoPath = telegramHelper.getUserPhotoPath(user)
if (photoPath != null) {
addGrayPhoto(user.id, photoPath)
}
val message = telegramHelper.getUserMessage(user) val message = telegramHelper.getUserMessage(user)
if (message != null) { if (message != null) {
app.showLocationHelper.addLocationToMap(message) app.showLocationHelper.addOrUpdateLocationOnMap(message)
} }
runOnUi { runOnUi {
listeners.forEach { it.get()?.onTelegramUserChanged(user) } listeners.forEach { it.get()?.onTelegramUserChanged(user) }
@ -255,6 +267,14 @@ class MainActivity : AppCompatActivity(), TelegramListener, ActionButtonsListene
} }
} }
override fun onReceiveChatLocationMessages(chatId: Long, vararg messages: TdApi.Message) {
addGrayPhoto(chatId)
}
override fun onDeleteChatLocationMessages(chatId: Long, messages: List<TdApi.Message>) {}
override fun updateLocationMessages() {}
override fun switchButtonsVisibility(visible: Boolean) { override fun switchButtonsVisibility(visible: Boolean) {
val buttonsVisibility = if (visible) View.VISIBLE else View.GONE val buttonsVisibility = if (visible) View.VISIBLE else View.GONE
if (buttonsBar.visibility != buttonsVisibility) { if (buttonsBar.visibility != buttonsVisibility) {
@ -331,6 +351,23 @@ class MainActivity : AppCompatActivity(), TelegramListener, ActionButtonsListene
} }
} }
private fun addGrayPhoto(chatId: Long) {
val chat = app.telegramHelper.getChat(chatId)
val chatIconPath = chat?.photo?.small?.local?.path
if (chat != null && chatIconPath != null) {
addGrayPhoto(app.telegramHelper.getUserIdFromChatType(chat.type), chatIconPath)
}
}
private fun addGrayPhoto(userId: Int, originalPhotoPath: String) {
if (userId != 0 && !app.telegramHelper.hasGrayscaleUserPhoto(userId)) {
app.uiUtils.convertAndSaveGrayPhoto(
originalPhotoPath,
"${app.filesDir.absolutePath}/$GRAYSCALE_PHOTOS_DIR$userId$GRAYSCALE_PHOTOS_EXT"
)
}
}
private fun isOsmAndInstalled() = AndroidUtils.isAppInstalled(this, settings.appToConnectPackage) private fun isOsmAndInstalled() = AndroidUtils.isAppInstalled(this, settings.appToConnectPackage)
private fun runOnUi(action: (() -> Unit)) { private fun runOnUi(action: (() -> Unit)) {

View file

@ -2,6 +2,7 @@ package net.osmand.telegram.utils
import android.Manifest import android.Manifest
import android.app.Activity import android.app.Activity
import android.content.ContentResolver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.pm.PackageManager import android.content.pm.PackageManager
@ -131,6 +132,14 @@ object AndroidUtils {
} }
} }
fun resourceToUri(ctx: Context, resID: Int): Uri {
return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
"://${ctx.resources.getResourcePackageName(resID)}" +
"/${ctx.resources.getResourceTypeName(resID)}" +
"/${ctx.resources.getResourceEntryName(resID)}"
)
}
fun isAppInstalled(ctx: Context, appPackage: String): Boolean { fun isAppInstalled(ctx: Context, appPackage: String): Boolean {
try { try {
ctx.packageManager.getPackageInfo(appPackage, 0) ctx.packageManager.getPackageInfo(appPackage, 0)

View file

@ -6,6 +6,7 @@ import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable import android.graphics.drawable.LayerDrawable
import android.hardware.Sensor import android.hardware.Sensor
import android.hardware.SensorManager import android.hardware.SensorManager
import android.os.AsyncTask
import android.support.annotation.ColorInt import android.support.annotation.ColorInt
import android.support.annotation.ColorRes import android.support.annotation.ColorRes
import android.support.annotation.DrawableRes import android.support.annotation.DrawableRes
@ -16,14 +17,21 @@ import android.view.WindowManager
import android.widget.ImageView import android.widget.ImageView
import android.widget.TextView import android.widget.TextView
import net.osmand.Location import net.osmand.Location
import net.osmand.PlatformUtil
import net.osmand.data.LatLon import net.osmand.data.LatLon
import net.osmand.telegram.R import net.osmand.telegram.R
import net.osmand.telegram.TelegramApplication import net.osmand.telegram.TelegramApplication
import net.osmand.telegram.ui.views.DirectionDrawable import net.osmand.telegram.ui.views.DirectionDrawable
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.* import java.util.*
class UiUtils(private val app: TelegramApplication) { const val GRAYSCALE_PHOTOS_DIR = "grayscale_photos/"
const val GRAYSCALE_PHOTOS_EXT = ".jpeg"
class UiUtils(private val app: TelegramApplication) {
private val drawableCache = LinkedHashMap<Long, Drawable>() private val drawableCache = LinkedHashMap<Long, Drawable>()
private val circleBitmapCache = LinkedHashMap<String, Bitmap>() private val circleBitmapCache = LinkedHashMap<String, Bitmap>()
@ -107,6 +115,16 @@ class UiUtils(private val app: TelegramApplication) {
return getDrawable(id, if (light) R.color.icon_light else 0) return getDrawable(id, if (light) R.color.icon_light else 0)
} }
fun convertAndSaveGrayPhoto(originalPhotoPath: String, greyPhotoPath: String) {
if (File(originalPhotoPath).exists()) {
ConvertPhotoToGrayscale().executeOnExecutor(
AsyncTask.THREAD_POOL_EXECUTOR,
originalPhotoPath,
greyPhotoPath
)
}
}
private fun createCircleBitmap(source: Bitmap, recycleSource: Boolean = false): Bitmap { private fun createCircleBitmap(source: Bitmap, recycleSource: Boolean = false): Bitmap {
val size = Math.min(source.width, source.height) val size = Math.min(source.width, source.height)
@ -208,4 +226,56 @@ class UiUtils(private val app: TelegramApplication) {
var screenOrientation: Int = 0 var screenOrientation: Int = 0
var outdatedLocation: Boolean = false var outdatedLocation: Boolean = false
} }
private class ConvertPhotoToGrayscale : AsyncTask<String, String, Void?>() {
private val log = PlatformUtil.getLog(ConvertPhotoToGrayscale::class.java)
override fun doInBackground(vararg params: String?): Void? {
val userOriginalPhotoPath = params[0]
val userGrayScalePhotoPath = params[1]
if (userOriginalPhotoPath != null && userGrayScalePhotoPath != null) {
convertToGrayscaleAndSave(userOriginalPhotoPath, userGrayScalePhotoPath)
}
return null
}
fun convertToGrayscaleAndSave(coloredImagePath: String, newFilePath: String) {
val currentImage = BitmapFactory.decodeFile(coloredImagePath)
val grayscaleImage = toGrayscale(currentImage)
saveBitmap(grayscaleImage, newFilePath)
}
private fun toGrayscale(bmpOriginal: Bitmap): Bitmap {
val bmpGrayscale = Bitmap.createBitmap(bmpOriginal.width, bmpOriginal.height, Bitmap.Config.ARGB_8888)
val c = Canvas(bmpGrayscale)
val paint = Paint()
val cm = ColorMatrix()
cm.setSaturation(0f)
val f = ColorMatrixColorFilter(cm)
paint.colorFilter = f
c.drawBitmap(bmpOriginal, 0f, 0f, paint)
return bmpGrayscale
}
private fun saveBitmap(bitmap: Bitmap, newFilePath: String) {
var fout: FileOutputStream? = null
try {
val file = File(newFilePath)
if (file.parentFile != null) {
file.parentFile.mkdirs()
}
fout = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout)
} catch (e: Exception) {
log.error(e)
} finally {
try {
fout?.close()
} catch (e: IOException) {
log.error(e)
}
}
}
}
} }