Home > Software design >  Getting picture from user in Android studio and encoding so it can be stored in the DB
Getting picture from user in Android studio and encoding so it can be stored in the DB

Time:11-22

I get an image from an user which is converted into a bitmap. I then convert the bitmap to a an byte array and send it over JSON to be stored in a database. Then when the user starts the particular activity I want the image to be retrieved form the database and displayed to the user.

My problem is that the bitmap that I get seems to be a reference to some memory on the device android.graphics.Bitmap@324a72b which changes every time I run the application although I select the same image. I want to be able to retrieve the actual bitmap so it can be stored in a DB. I'm also not using as web server for storing the images since its a smaller project.

b.buttonNewItemUpImg.setOnClickListener {
            val openGalleryIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            startActivityForResult(openGalleryIntent, ResultLoadImage)
        }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == ResultLoadImage){
            if (resultCode == Activity.RESULT_OK){
                var temp = MediaStore.Images.Media.getBitmap(this.contentResolver, data!!.getData())
                bitmap = getResizedBitmap(temp!!, maxImageSize)
                b.imageView.setImageURI(data!!.getData())
            }
        }
    }

The getResizedBitmap() function simply makes the image smaller.

CodePudding user response:

As described in https://stackoverflow.com/a/57576381/6359367

Use this

      var temp = ImageDecoder.createSource(this.getContentResolver(), data!!.getData())
      bitmap = ImageDecoder.decodeBitmap(temp);

beware this code was java I tried to adapt it to kotlin you may need to tweak it a bit

CodePudding user response:

Instead of storing the whole image in the database, you should copy images to the app's local storage and then store, path of these copied images to the database, which you can use later to retrieve the images.

Copying image to the app's local storage after getting the selected image uri

//creating an image file in the app's local storage
val dir = requireActivity().getDir(FOLDER_TO_SAVE, Context.MODE_PRIVATE).path
val copiedImageFile = File(dir, UUID.randomUUID().toString()   ".jpg")
val copiedImageUri = Uri.fromFile(copiedImageFile)

//copying selected image to the local storage
data!!.getData().path?.let {
    File(it).copyTo(copiedImageFile)
}

Get path of the above copied image, using its uri

copiedImageUri.path.?.let{
     val copiedImagePath = "file://$it"
     //now save this path to your database
}

Use this saved image path to retrieve the image in any fragment or activity.

  • Related