I a having a problem in load picture in an imageview through uri. I am using picasso and my code is as below:
I have an object CreateImage with a function displayImageFromURI
fun displayImageFromURI(imageView: ImageView,uri: Uri?,context: Context){
Log.e("url", uri.toString())
Picasso.get()
.load(uri)
.fit().centerCrop()
.into(imageView, object: com.squareup.picasso.Callback {
override fun onSuccess() {
val imageBitmap = (imageView.drawable as BitmapDrawable).bitmap
val imageDrawable =
RoundedBitmapDrawableFactory.create(context.resources, imageBitmap)
imageView.setImageDrawable(imageDrawable)
}
override fun onError(e: java.lang.Exception?) {
Log.e("error",e.toString())
}
})
}
I am calling this function from a fragment as below:
if (!photoUrl.equals("")) {
Log.e("in photo url", photoUrl)
val image = Uri.parse(photoUrl)
CreateImage.displayImageFromURI(ivUploadQuestionImage, image, this)
}
but my image is not being loaded in the imageview. The string photoUrl contains the link in string format as well. Can anybody please help me?
Related
I'm trying to return the bitmap value from a lambda function but I get the error: lateinit property bitmap has not been initialized ... Is there a way to check if the ImageRequest is complete before returning the bitmap?
fun getBitmap(context:Context,imageUrl: String) : Bitmap{
lateinit var bitmap: Bitmap
val imageRequest = ImageRequest.Builder(context)
.data(imageUrl)
.target { drawable ->
bitmap = drawable.toBitmap() // This is the bitmap 🚨
}
.build()
ImageLoader(context).enqueue(imageRequest)
return bitmap
}
Hm... I don't have much time to explain. Just see the code and understand.
You have to use execute() instead of enqueue(). See
private suspend fun getBitmap(context: Context, url: String): Bitmap? {
var bitmap: Bitmap? = null
val request = ImageRequest.Builder(context)
.data(url)
.target(
onStart = {
Log.d(TAG, "Coil loader started.")
},
onSuccess = { result ->
Log.e(TAG, "Coil loader success.")
bitmap = result.toBitmapOrNull() // Or (result as BitmapDrawable).bitmap
},
onError = {
Log.e(TAG, "Coil loading error")
}
)
.build()
context.imageLoader.execute(request)
return bitmap
}
I want to when user is offline, the image from firebase storage that retrived in an imageview when he/she was online, be visible, but I can't implement that codes, as a beginner in android studio and kotlin.
I want add Glide image cache and loader to this :
private fun getUserProfile() {
val navigationView = binding.navView
val header: View = navigationView.getHeaderView(0)
storageReference = FirebaseStorage.getInstance().reference.child("Users/$uid")
val localeFile = File.createTempFile("tempFile","")
storageReference.getFile(localeFile).addOnSuccessListener {
val bitmap = BitmapFactory.decodeFile(localeFile.absolutePath)
val imageView = header.findViewById<ImageView>(R.id.circleImageView)
imageView.setImageBitmap(bitmap)
}.addOnFailureListener{
finish()
}
}
but I don't know how to add below codes to above one correctly :
Glide.with(this)
.load(url)
.into(imageView);
I added like below but in offline still not load :
private fun getUserProfile() {
val navigationView = binding.navView
val header: View = navigationView.getHeaderView(0)
storageReference = FirebaseStorage.getInstance().reference.child("Users/$uid")
val localeFile = File.createTempFile("tempFile","")
storageReference.getFile(localeFile).addOnSuccessListener {
val bitmap = BitmapFactory.decodeFile(localeFile.absolutePath)
val imageView = header.findViewById<ImageView>(R.id.circleImageView)
Glide.with(this)
.load(bitmap)
.into(imageView)
}.addOnFailureListener{
finish()
}
}
I'm trying to create an image crop functionality using CropImageView from ArthurHub's Library and I have a string URL like https://mywebsite.com/library/folder/KeYO8Ff31l178kO.png. Is possible to parse this link to URI or Bitmap so I can use setImageUriAsync or setImageBitmap to set the image? I'm using Kotlin. Thanks
LATER EDIT:
I found the solution, I'm not sure if it's the best but maybe will be useful:
I created this inner class and inside it I parsed the url to bitmap and in OnPostExecute method I set the resource for cropImageView.
Code:
internal class GetBitmapFromUrlAsync(private val cropImageView: CropImageView) : AsyncTask<String, Void?, Bitmap>() {
override fun doInBackground(vararg src: String): Bitmap? {
val url = URL(src[0])
val bitmap: Bitmap
try {
val connection = url.openConnection() as HttpsURLConnection
connection.doInput = true
connection.connect()
val input: InputStream = connection.inputStream
bitmap = BitmapFactory.decodeStream(input)
} catch (e: Exception) {
e.printStackTrace()
return null
}
return bitmap
}
override fun onPostExecute(bitmap: Bitmap?) {
cropImageView.setImageBitmap(bitmap)
}
}
My application uses the camera to take pictures and then saves them in the MediaStore. I would like to put these pictures in my RecyclerView using Glide but I don't know how to do it.
A function that saves the image:
private fun imageCapture() {
// Set desired name and type of captured image
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, "${what_is_that_insect_tv.text}")
put(MediaStore.MediaColumns.DATE_MODIFIED.format("MM/dd/yyyy"), (Calendar.getInstance().timeInMillis / 1000L))
put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg")
}
// Create the output file option to store the captured image in MediaStore
val outputFileOptions = ImageCapture.OutputFileOptions
.Builder(resolver, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
.build()
// Initiate image capture
imageCapture?.takePicture(
outputFileOptions,
cameraExecutor,
object : ImageCapture.OnImageSavedCallback {
override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
// Image was successfully saved to `outputFileResults.savedUri`
}
override fun onError(exception: ImageCaptureException) {
val errorType = exception.imageCaptureError
Toast.makeText(requireContext(), "$errorType", Toast.LENGTH_SHORT).show()
}
})
}
Function in Adapter
fun bind(insect: Insect){
with(itemView){
name_insect_item.text = insect.name
Glide.with(this)
.load()
.into(this.image_insect_item)
}
}
In order to use Glide you must obtain the URI of the saved image, in the onImageSaved I believe you can call .getSavedUri() like so :
override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
val uri = ImageCapture.OutputFileResults.getSavedUri()
}
You should then be able to use the Uri in an ArrayList you feed to the adaptor. Got it from here :
https://developer.android.com/reference/androidx/camera/core/ImageCapture.OutputFileResults#getSavedUri()
I do this in my code like this:
Glide.with(holder.imageView.getContext())
.load(new File(hotel.imageId2))
.into(holder.imageView)
also this might help:
RecyclerView- Glide
I need to send a specific image from my recyclerview that has been clicked to the new activity that will display the image. The question is how do I convert my image to bitmap or something like that so I can send them using intent?
Here's my code:
RecyclerViewAdapter.kt
class ViewHolder(view: View) : RecyclerView.ViewHolder(view){
fun bindItem(items: Item) {
itemView.name.text = items.name
itemView.desc.text = items.desc
Glide.with(itemView.context).load(items.image).into(itemView.image)
itemView.setOnClickListener {
itemView.context.startActivity(itemView.context.intentFor<DetailsActivity>("image" to bitmap, "name" to items.name, "desc" to items.desc))
}
}
}
SecondActivity
val intent = intent
name = intent.getStringExtra("name")
image = intent.getStringExtra("image")
desc = intent.getStringExtra("desc")
nameTextView.text = name
descTextView.text = desc
Glide.with(this)
.load(image)
.into(imgPhotos)
I have already tried all the code that are provided on this site, but they all didn't work. Thanks!
I am not using Glide but it should be like this.
lateinit imageBitmap : Bitmap
Glide.with(this).asBitmap().load("YOUR_URL").into(object: Target<Bitmap>{
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
imageBitmap = resource
}
})
You can send Bitmap directly because it is Parcelable
intent.putExtra("image",imageBitmap)
To getBitmap
val bitmap = intent.extras.getParcelable<Bitmap>("image")
Convert the image to byteArray and pass it through intent. Extract the data through intent on the other side and convert byteArray into bitmap.