How to crop image with known path based on user selection Android Studio (Ucrop or another library) - ucrop

I've a question, how can i crop an image if i know the imagePath? I know the imagePath, because the user selects an image from the gallery that we provide.
private val getContent = registerForActivityResult(ActivityResultContracts.GetContent()){ uri ->
val inputUri = uri
val outputUri = File(filesDir,"croppedImage.jpg").toUri()
val listUri = listOf<Uri>(inputUri,outputUri)
cropImage.launch(listUri)
}
private val uCropContract = object: ActivityResultContract<List<Uri>,Uri>(){
override fun createIntent(context: Context, input: List<Uri>): Intent {
val inputUri = input[0]
val outputUri = input[1]
val uCrop = UCrop.of(inputUri, outputUri)
.withAspectRatio(5f,5f)
.withMaxResultSize(1080,1080)
return uCrop.getIntent(context)
}
override fun parseResult(resultCode: Int, intent: Intent?): Uri {
return UCrop.getOutput(intent!!)!!
}
}
private val cropImage = registerForActivityResult(uCropContract){ uri ->
binding.imvImageAdded.setImageURI(uri)
}

Related

Kotlin MVVM, How to get the latest value from Entity in ViewModel?

I have created an app where I try to insert a record with the latest order number increased by one.
The main function is triggered from Activity, however, the whole process is in my ViewModel.
Issue no 1, After I insert a new record the order by number is not updated.
Issue no 2, When I insert first record the order by number is null, for that reason I am checking for null and setting the value to 0.
My goal here is to get the latest order_by number from Entity in my ViewModel, increased by 1 and add that new number to my new record using fun addTestData(..).
Entity:
#Entity(tableName = "word_table")
data class Word(
#ColumnInfo(name = "id") val id: Int,
#ColumnInfo(name = "word") val word: String,
#ColumnInfo(name = "order_by") val orderBy: Int
Dao:
#Query("SELECT order_by FROM word_table ORDER BY order_by DESC LIMIT 1")
suspend fun getHighestOrderId(): Int
Repository:
#Suppress("RedundantSuspendModifier")
#WorkerThread
suspend fun getHighestOrderId(): Int {
return wordDao.getHighestOrderId()
}
ViewModel:
private var _highestOrderId = MutableLiveData<Int>()
val highestOrderId: LiveData<Int> = _highestOrderId
fun getHighestOrderId() = viewModelScope.launch {
val highestOrderId = repository.getHighestOrderId()
_highestOrderId.postValue(highestOrderId)
}
fun addTestData(text: String) {
for (i in 0..1500) {
getHighestOrderId()
var highestNo = 0
val highestOrderId = highestOrderId.value
if (highestOrderId == null) {
highestNo = 0
} else {
highestNo = highestOrderId
}
val addNumber = highestNo + 1
val word2 = Word(0, text + "_" + addNumber,addNumber)
insertWord(word2)
}
}
Activity:
wordViewModel.addTestData(text)

Kotlin : copy image to gallery

I am trying to copy an image that is stored in my application folder to a predefined folder in my gallery.
I started from an image sharing code..
This is my code :
val extension = when (requireNotNull(pictureResult).format) {
PictureFormat.JPEG -> "jpg"
PictureFormat.DNG -> "dng"
else -> throw RuntimeException("Unknown format.")
}
val timestamp = System.currentTimeMillis()
val namePhoto = "picture_"+timestamp+"."+extension;
val destFile = File(filesDir, namePhoto)
val folder = "/CustomFolder"
CameraUtils.writeToFile(requireNotNull(pictureResult?.data), destFile) { file ->
if (file != null) {
// Code to share - it works
/*
val context = this#PicturePreviewActivity
val intent = Intent(Intent.ACTION_SEND)
intent.type = "image/*"
val uri = FileProvider.getUriForFile(context, context.packageName + ".provider", file)
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(intent)
*/
*/
// Code to save image to gallery - doesn't work :(
val photoDirectory = File(Environment.DIRECTORY_PICTURES+folder, namePhoto)
val sourcePath = Paths.get(file.toURI())
Log.i("LOG","sourcePath : "+sourcePath.toString()) // /data/user/0/com.app.demo/files/picture_1663772068143.jpg
val targetPath = Paths.get(photoDirectory.toURI())
Log.i("LOG","targetPath : "+targetPath.toString()) // /Pictures/CustomFolder/picture_1663772068143.jpg
Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING)
// Error here but I don't know why
} else {
Toast.makeText(this#PicturePreviewActivity, "Error while writing file.", Toast.LENGTH_SHORT).show()
}
}
How do I copy the image to a predefined folder?
Ok, I did it !
Solution :
val folder = "/CustomFolder/" // name of your folder
val timestamp = System.currentTimeMillis()
val namePicture = "picture_"+timestamp+"."+extension;
try {
val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+folder);
if (!path.exists()) {
path.mkdir();
}
val pathImage = File(path,namePicture)
val stream = FileOutputStream(pathImage)
stream.write(imageByteArray).run {
stream.flush()
stream.close()
}
} catch (e: FileNotFoundException) {
e.printStackTrace()
}

How to return result from dto?

I'm trying to map entities to dtos and return a result, but it return as null for some reason. What am I doing wrong?
#PutMapping("/contract")
fun getContract(#RequestParam itemId: Int, #RequestParam id: Int): InventoryItemDTO {
var item: InventoryItem = inventoryItemService.getInventoryItemById(itemId)
val i = convertToItemDTO(item)
var con = contractService.getContractById(id)
val c = convertToContractDTO(con)
item.contract = con
i.contractDTO = c
//inventoryItemService.saveInventoryItem(i)
return i
}
fun convertToItemDTO(item: InventoryItem): InventoryItemDTO {
val itemDTO = modelMapper.map(item, InventoryItemDTO::class.java)
itemDTO.contractDTO = convertToContractDTO(item.contract!!)
return itemDTO
}
fun convertToContractDTO(contract: Contract): ContractDTO {
return modelMapper.map(contract, ContractDTO::class.java)
}

setShortcutInfo in NotificationCompat.Builder and pushDynamicShortcut in ShortcutManagerCompat doesn't work in Api 30(Android 11)

I am working on Bubbles in Android 11 and some functions doesn't work
I don't know how to fix this.
Android Studio writes:
Unresolved reference: setShortcutInfo
My NotificationCompat.Builder:
val builder = NotificationCompat.Builder(
appContext,
CHANNEL_WHATEVER
)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Um, hi!")
.setShortcutId("Settings")
.setShortcutInfo(shortcutInfo)
.setBubbleMetadata(bubble)
And my ShortcutInfoCompat.Builder:
val shortcutInfo = ShortcutInfoCompat.Builder(this, SHORTCUT_ID)
.setLongLived(true)
.setShortLabel("Settings")
.setIntent(Intent(Settings.ACTION_SETTINGS))
.setIcon(IconCompat.createWithResource(this, R.drawable.ic_launcher_foreground))
.build()
ShortCutManagerCompat with pushdynamicshortcut returns:
Unresolved reference: pushDynamicShortcut
I Copy/Pasted code from this:
Gitlab
Thanks.
I added mutableListOf for ShortcutInfo. So, working example:
private var channelCreated = false
private val notifId = 1337
private val notifChannel = "Bubble Manager"
private val shortcutId = "Bubble Manager"
val bubble = showBubble()
#RequiresApi(Build.VERSION_CODES.R)
private fun buildBubbleNotification(appContext: Context): Notification {
val pi = PendingIntent.getActivity(
appContext,
0,
Intent(appContext, BubbleActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT
)
val bubble = NotificationCompat.BubbleMetadata.Builder()
.setDesiredHeight(4000)
.setIcon(IconCompat.createWithResource(appContext, R.drawable.ic_logo_bubble))
.setIntent(pi)
.apply { setAutoExpandBubble(true); setSuppressNotification(true) }
.build()
ShortcutManagerCompat.addDynamicShortcuts(
context, mutableListOf(
ShortcutInfoCompat.Builder(context, shortcutId)
.setLongLived(true)
.setShortLabel("Bubble Manager")
.setIntent(Intent(Settings.ACTION_SETTINGS))
.setIcon(IconCompat.createWithResource(context, R.drawable.ic_logo_bubble))
.build()
)
)
val builder = NotificationCompat.Builder(
appContext,
notifChannel
)
.setSmallIcon(R.drawable.ic_logo_bubble)
.setContentTitle("Title")
.setShortcutId("Bubble Manager")
.setShortcutId(shortcutId)
.setBubbleMetadata(bubble)
val person = Person.Builder()
.setBot(true)
.setName("A Bubble Bot")
.setImportant(true)
.build()
val style = NotificationCompat.MessagingStyle(person)
.setConversationTitle("Bubble Manager")
style.addMessage("It's Bubble Manager", System.currentTimeMillis(), person)
builder.setStyle(style)
return builder.build()
}
#RequiresApi(Build.VERSION_CODES.R)
fun showBubble() {
NotificationManagerCompat.from(context).let { mgr ->
if (!channelCreated) {
mgr.createNotificationChannel(
NotificationChannel(
notifChannel,
"Whatever",
NotificationManager.IMPORTANCE_DEFAULT
)
)
channelCreated = true
}
mgr.notify(notifId, buildBubbleNotification(context))
}
}

How to mirror dragonbones animation?

I make KorGE game with dragonbone animation. How to mirror this dragonbones animation? I want to character look to the right instead of the left:)
val factory = KorgeDbFactory()
val skeDeferred = asyncImmediately { Json.parse(resourcesVfs["Ubbie/Ubbie_ske.json"].readString())!! }
val texDeferred = asyncImmediately { resourcesVfs["Ubbie/Ubbie_tex.json"].readString() }
val imgDeferred = asyncImmediately { resourcesVfs["Ubbie/Ubbie_tex.png"].readBitmap().mipmaps() }
factory.parseDragonBonesData(skeDeferred.await())
factory.parseTextureAtlasData(Json.parse(texDeferred.await())!!, imgDeferred.await())
val armatureDisplay = factory.buildArmatureDisplay("ubbie")!!.position(600, 720).scale(1)
armatureDisplay.animation.play("walk")
addUpdater {
this += armatureDisplay
}
SCALE_X = -1 gives mirror effect
val SCALE_X=-1
val SCALE_Y=1
...
val armatureDisplay = factory.buildArmatureDisplay("ubbie")!!.position(600, 720).scale(SCALE_X, SCALE_Y)

Resources