I am creating a simple camera app where with a click of a button, the camera is opened and once the image is clicked, it is displayed in the image view. But, I am unable to display the image captured in my imageview. Here are the XML and Kotlin codes:
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/welcome_text"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:textSize="24sp"
android:textStyle="bold"
android:textColor="#color/black" />
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/buttonId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:padding="15dp"
android:text="#string/camera_text"
android:textColor="#color/black"
android:textSize="18sp"
android:layout_gravity="center_horizontal"/>
<ImageView
android:id="#+id/imageId"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:scaleType="centerCrop"
android:visibility="visible"
android:layout_marginTop="20dp"/>
</LinearLayout>
Kotlin (MainActivity)
package com.example.cameraapp
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.activity_main.*
import java.util.jar.Manifest
class MainActivity : AppCompatActivity() {
companion object{
private const val CAMERA_PERMISSION_CODE = 1
private const val CAMERA_REQUEST_CODE = 2
}
var getImage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val data: Intent? = result.data
if (result.resultCode == CAMERA_REQUEST_CODE) {
val thumbNail: Bitmap = data!!.extras!!.get("data") as Bitmap
imageId.setImageBitmap(thumbNail)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
buttonId.setOnClickListener {
if(ContextCompat.checkSelfPermission(
this, android.Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED ){
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
getImage.launch(intent)
}else{
ActivityCompat.requestPermissions(
this, arrayOf(android.Manifest.permission.CAMERA),
CAMERA_PERMISSION_CODE
)
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode == CAMERA_PERMISSION_CODE){
if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
getImage.launch(intent)
}else{
Toast.makeText(this#MainActivity, "Permission Denied!!",
Toast.LENGTH_LONG).show()
}
}
}
}
Please help me find a solution. Thanks!
JAVA CODE
private void takeImageFromCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, getString(R.string.new_picture));
values.put(MediaStore.Images.Media.DESCRIPTION, getString(R.string.from_your_camera));
cameraUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
startActivityForResult(intent, CAMERA_IMAGE_CODE);
photoLinearLayoutVw.setVisibility(View.GONE);
dimImageVw.setVisibility(View.GONE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
try {
this.requestCode = requestCode;
this.resultCode = resultCode;
this.data = data;
descEditText.setText("");
descriptionEditDialogVw.setVisibility(View.VISIBLE);
} catch (Exception e) {
L.wtf(e);
}
} else {
Toast.makeText(getApplicationContext(), getString(R.string.unable_fetch_image), Toast.LENGTH_LONG).show();
}
}
You may want to launch a ActivityResultContracts.TakePicture() ActivityResultContract.
First, define a Uri where the image will be saved:
private val imageFile = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "filename")
private val uri = FileProvider.getUriForFile(
this,
"${applicationContext.packageName}.provider",
imageFile
)
Then, register your activity listener:
private val getImage = registerForActivityResult(ActivityResultContracts.TakePicture()) { success ->
if (success) {
// Image is available at the specified uri...
}
}
Finally, launch the ActivityResultContract with:
getImage.launch(uri)
Make sure that you have defined the necessary FileProvider in your AndroidManifest.xml file.
For more information on ActivityResultContracts.TakePicture see the official docs
Related
i am making my first app using kotlin and while i was making it i approached the problem of the camera app not opening when i click on a button. i have no idea what im doing wrong. I get the error camera keeps stopping
import android.app.Activity
import android.content.ClipData
import android.content.Intent
import android.graphics.Bitmap
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
private const val REQUEST_CODE = 42
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val takePicBtn = findViewById<Button>(R.id.takePicBtn) as Button
takePicBtn.setOnClickListener{
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if(takePictureIntent.resolveActivity(this.packageManager)!= null) {
startActivityForResult(takePictureIntent, REQUEST_CODE)
} else{
Toast.makeText(this , "Unable to open camera", Toast.LENGTH_SHORT).show()
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?){
val imagePic = findViewById<ImageView>(R.id.image) as ImageView
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK){
val takenImage = data?.extras?.get("data") as Bitmap
imagePic.setImageBitmap(takenImage)
}else{
super.onActivityResult(requestCode, resultCode, data)
}
}
}
Try doing it using the below code. And i am assuming you have added permissions as well.
takePicBtn.setOnClickListener{
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
var photoFile: File? = null
try {
photoFile =
createImageFile(context!!)
} catch (ex: IOException) {
ex.printStackTrace()
}
if (photoFile != null) {
photoURI = context?.let { photoURIFile(it, photoFile) }
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(
cameraIntent,
REQUEST_CODE
)
}
}
If you still face any issue feel free to ask
I am beginner to android studio and just started learning Kotlin. I have a problem: I cannot add a picture from the camera or from the gallery to the ImageView in a fragment. Help me please:( I've seen examples with bitmap, but it doesn't work for Activity and Fragment.
I inserted onActivityResult, but the photo from the camera did not appear in the imageView. I do not understand how to correctly link to the imageView.
P.S. Sorry for my bad English:)
HomeFragment.kt
package com.example.avtoinspector111.ui.home
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.avtoinspector111.R
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
const val Image_Capture_Code = 24
const val REQUEST_CODE=24
const val REQUEST_TAKE_PHOTO=24
class HomeFragment : Fragment() {
lateinit var imageView: ImageView
lateinit var button: Button
private val pickImage = 100
private var imageUri: Uri? = null
private lateinit var homeViewModel: HomeViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_home, container, false)
//val textView: TextView = root.findViewById(R.id.text_home)
// homeViewModel.text.observe(viewLifecycleOwner, Observer {
// textView.text = it
// })
// вызов галереи
val btn1: Button = root.findViewById(R.id.buttongallery)
btn1.setOnClickListener {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, REQUEST_CODE)
}
// вызов камеры
var btn: Button = root.findViewById(R.id.buttoncamera)
btn.setOnClickListener {
val bInt = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(bInt, REQUEST_CODE)
}
return root
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode== REQUEST_CODE && requestCode == Activity.RESULT_OK){
val image=data?.extras?.get("data") as Bitmap
imageView.setImageBitmap(image)
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
}
Open Camera and take a picture method
private void takeCameraImage() {
Dexter.withActivity(this)
.withPermissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if (report.areAllPermissionsGranted()) {
fileName = System.currentTimeMillis() + ".jpg";
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, getCacheImagePath(fileName));
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
Open Gallery and take an image
private void chooseImageFromGallery() {
Dexter.withActivity(this)
.withPermissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if (report.areAllPermissionsGranted()) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, REQUEST_GALLERY_IMAGE);
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
on activity method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_IMAGE_CAPTURE:
if (resultCode == RESULT_OK) {
cropImage(getCacheImagePath(fileName));
} else {
setResultCancelled();
}
break;
case REQUEST_GALLERY_IMAGE:
if (resultCode == RESULT_OK) {
Uri imageUri = data.getData();
cropImage(imageUri);
} else {
setResultCancelled();
}
break;
case UCrop.REQUEST_CROP:
if (resultCode == RESULT_OK) {
handleUCropResult(data);
} else {
setResultCancelled();
}
break;
case UCrop.RESULT_ERROR:
final Throwable cropError = UCrop.getError(data);
Log.e(TAG, "Crop error: " + cropError);
setResultCancelled();
break;
default:
setResultCancelled();
}
}
You can remove the crop function you want
Create a path (file for an image taken from a camera )
private Uri getCacheImagePath(String fileName) {
File path = new File(getExternalCacheDir(), "camera");
if (!path.exists()) path.mkdirs();
File image = new File(path, fileName);
return getUriForFile(ImagePickerActivity.this, getPackageName() + ".provider", image);
}
In your manifest file
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
Hope It will help if not comment down
code from the android hive
I am trying to place an image from internal storage into the background of a button. There are no error messages. I can open the storage on the emulated device and select and image, but it doesn't get placed/inserted into the button background. I am using Android 4.1 and using API Level 30 (Q) / Android 11. I am coding in Kotlin.
The Log says the photo is selected.
The code in question is this:
RegisterActivity.kt --partial--
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == 0 && resultCode == RESULT_OK && data != null){
// proceed and check what the selected image was...
Log.d("RegisterActivity", "Photo was selected")
val uri = data.data
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri)
val bitmapDrawable = BitmapDrawable(bitmap)
select_photo_button_register.setBackgroundDrawable(bitmapDrawable)
select_photo_button_register.text = ""
}
}
RegisterActivity.kt --FULL--
package <censored>.kotlinmessenger
import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import kotlinx.android.synthetic.main.activity_register.*
class RegisterActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
this.supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
supportActionBar?.setDisplayShowCustomEnabled(true)
supportActionBar?.setCustomView(R.layout.custom_action_bar)
//getSupportActionBar().setElevation(0);
register_button_register.setOnClickListener {
performRegister()
}
already_have_account_textView.setOnClickListener {
Log.d("RegisterActivity", "Trying to show login activity.")
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
}
select_photo_button_register.setOnClickListener {
Log.d("RegisterActivity", "Try to show photo selector")
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, 0)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == 0 && resultCode == RESULT_OK && data != null){
// proceed and check what the selected image was...
Log.d("RegisterActivity", "Photo was selected")
val uri = data.data
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri)
val bitmapDrawable = BitmapDrawable(bitmap)
select_photo_button_register.setBackgroundDrawable(bitmapDrawable)
select_photo_button_register.text = ""
}
}
private fun performRegister() {
val email = email_editText_register.text.toString()
val password = password_editText_register.text.toString()
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(this, "Please check email/password", Toast.LENGTH_SHORT).show()
return
}
Log.d("RegisterActivity", "Email: $email")
Log.d("RegisterActivity", "Password: $password")
//Firebase Auth
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
.addOnCompleteListener {
if (!it.isSuccessful) return#addOnCompleteListener
// else if successful
val uid = it.result?.user?.uid
Log.d("RegisterActivity", "Successfully created user with uid: $uid")
println("Email: $email\n Password: $password\n UID: $uid")
}
.addOnFailureListener {
Log.d("Main", "Failed to create user: ${it.message}")
Toast.makeText(this, "Failed to create user: ${it.message}", Toast.LENGTH_SHORT)
.show()
}
}
}
activity_register.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#86B400"
tools:context=".RegisterActivity" >
<EditText
android:id="#+id/username_editText_register"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginStart="36dp"
android:layout_marginLeft="36dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="36dp"
android:layout_marginRight="36dp"
android:background="#drawable/rounded_edittext"
android:ems="10"
android:hint="Username"
android:inputType="textPersonName"
android:paddingLeft="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/select_photo_button_register" />
<EditText
android:id="#+id/email_editText_register"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginTop="8dp"
android:background="#drawable/rounded_edittext"
android:ems="10"
android:hint="Email"
android:inputType="textEmailAddress"
android:paddingLeft="16dp"
app:layout_constraintEnd_toEndOf="#+id/username_editText_register"
app:layout_constraintStart_toStartOf="#+id/username_editText_register"
app:layout_constraintTop_toBottomOf="#+id/username_editText_register" />
<EditText
android:id="#+id/password_editText_register"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginTop="8dp"
android:background="#drawable/rounded_edittext"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
android:paddingLeft="16dp"
app:layout_constraintEnd_toEndOf="#+id/email_editText_register"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="#+id/email_editText_register"
app:layout_constraintTop_toBottomOf="#+id/email_editText_register"
/>
<Button
android:id="#+id/register_button_register"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="#drawable/rounded_edittext"
android:text="Register"
app:backgroundTint="#android:color/holo_green_dark"
app:layout_constraintEnd_toEndOf="#+id/password_editText_register"
app:layout_constraintStart_toStartOf="#+id/password_editText_register"
app:layout_constraintTop_toBottomOf="#+id/password_editText_register" />
<TextView
android:id="#+id/already_have_account_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Do you already have an account?"
android:textColor="#FFFFFF"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="#+id/register_button_register"
app:layout_constraintStart_toStartOf="#+id/register_button_register"
app:layout_constraintTop_toBottomOf="#+id/register_button_register" />
<Button
android:id="#+id/select_photo_button_register"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginTop="32dp"
android:background="#drawable/rounded_select_photo"
android:text="Select photo"
android:textColor="#color/black"
app:backgroundTint="bitmapDrawable"
app:layout_constraintBottom_toTopOf="#+id/username_editText_register"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
RegisterActivity with External Storage permission
package <censroed>.kotlinmessenger
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.ImageDecoder
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.storage.FirebaseStorage
import kotlinx.android.synthetic.main.activity_register.*
import java.util.*
class RegisterActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
register_button_register.setOnClickListener {
performRegister()
}
already_have_account_textView.setOnClickListener {
Log.d("RegisterActivity", "Trying to show login activity.")
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
}
select_photo_button_register.setOnClickListener {
Log.d("RegisterActivity", "Try to show photo selector")
val galleryIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(galleryIntent, 0)
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, 0)
}
}
var selectedPhotoUri: Uri? = null
#RequiresApi(Build.VERSION_CODES.P)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (ContextCompat.checkSelfPermission(this#RegisterActivity,
Manifest.permission.READ_EXTERNAL_STORAGE) !==
PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this#RegisterActivity,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(this#RegisterActivity,
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
} else {
ActivityCompat.requestPermissions(this#RegisterActivity,
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
}
}
selectedPhotoUri = data?.data
// val source = ImageDecoder.createSource(this.contentResolver, selectedPhotoUri!!)
// val bitmap = ImageDecoder.decodeBitmap(source)
//// select_photo_button_register.setBackgroundDrawable(BitmapDrawable(this.resources, bitmap))
// select_photo_button_register.background = BitmapDrawable(resources, bitmap)
// try {
// selectedPhotoUri?.let {{
// val source = ImageDecoder.createSource(this.contentResolver, selectedPhotoUri!!)
// val bitmap = ImageDecoder.decodeBitmap(source)
//
// }
// select_photo_button_register.setBackgroundDrawable(BitmapDrawable(this.resources, bitmap))
//
// }
// } catch (e: Exception) {
// e.printStackTrace()
// }
// if (requestCode == 0 && resultCode == Activity.RESULT_OK && data != null){
// Log.d("RegisterActivity", "Photo was selected")
//
// selectedPhotoUri = data.data
// val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedPhotoUri)
// val bitmapDrawable = BitmapDrawable(bitmap)
// select_photo_button_register.setBackgroundDrawable(bitmapDrawable)
// }
}
#RequiresApi(Build.VERSION_CODES.P)
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
grantResults: IntArray) {
when (requestCode) {
1 -> {
if (grantResults.isNotEmpty() && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
if ((ContextCompat.checkSelfPermission(this#RegisterActivity,
Manifest.permission.ACCESS_FINE_LOCATION) ===
PackageManager.PERMISSION_GRANTED)) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show()
val source = ImageDecoder.createSource(this.contentResolver, selectedPhotoUri!!)
val bitmap = ImageDecoder.decodeBitmap(source)
// select_photo_button_register.setBackgroundDrawable(BitmapDrawable(this.resources, bitmap))
select_photo_button_register.background = BitmapDrawable(resources, bitmap)
}
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
}
return
}
}
}
private fun performRegister() {
val email = email_editText_register.text.toString()
val password = password_editText_register.text.toString()
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(this, "Please check email/password", Toast.LENGTH_SHORT).show()
return
}
Log.d("RegisterActivity", "Email: $email")
Log.d("RegisterActivity", "Password: $password")
//Firebase Auth
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
.addOnCompleteListener {
if (!it.isSuccessful) return#addOnCompleteListener
// else if successful
val uid = it.result?.user?.uid
Log.d("RegisterActivity", "Successfully created user with uid: $uid")
uploadImageToFirebase()
}
.addOnFailureListener {
Log.d("RegisterActivity", "Failed to create user: ${it.message}")
Toast.makeText(this, "Failed to create user: ${it.message}", Toast.LENGTH_SHORT)
.show()
}
}
private fun uploadImageToFirebase() {
if (selectedPhotoUri == null) return
val filename = UUID.randomUUID().toString()
val ref = FirebaseStorage.getInstance().getReference("/images/$filename")
ref.putFile(selectedPhotoUri!!).addOnSuccessListener {
Log.d("RegisterActivity", "Sucessfully uploaded image: ${it.metadata?.path}")
}
}
}
Try using this since MediaStore.Images.Media.getBitmap() is depreceated.
try {
uri?.let {
if(Build.VERSION.SDK_INT < 28) {
val bitmap = MediaStore.Images.Media.getBitmap(
this.contentResolver,
uri
)
} else {
val source = ImageDecoder.createSource(this.contentResolver, uri)
val bitmap = ImageDecoder.decodeBitmap(source)
}
select_photo_button_register.setBackgroundDrawable(new BitmapDrawable(context.getResources(), bitmap));
}
} catch (e: Exception) {
e.printStackTrace()
}
Try this. Replace these two lines:
val bitmapDrawable = BitmapDrawable(bitmap)
select_photo_button_register.setBackgroundDrawable(bitmapDrawable)
with this:
select_photo_button_register.background = BitmapDrawable(resources, bitmap)
I fixed it. I changed the Button to an ImageView and added a TextView over it. I am using Picasso to insert it into the ImageView.
The onActivityResult deals with inserting the image.
Permissions code obtained from here
package <censored>.kotlinmessenger
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_register.*
class RegisterActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
register_button_register.setOnClickListener {
performRegister()
}
already_have_account_textView.setOnClickListener {
Log.d("RegisterActivity", "Trying to show login activity.")
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
}
//BUTTON CLICK
select_photo_imageView_register.setOnClickListener {
//check runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED
) {
//permission denied
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
val permissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
//show popup to request runtime permission
requestPermissions(permissions, PERMISSION_CODE)
} else {
//permission already granted
Toast.makeText(this, "Permission already granted", Toast.LENGTH_SHORT).show()
pickImageFromGallery()
}
} else {
//system OS is < Marshmallow
pickImageFromGallery()
}
}
}
private fun pickImageFromGallery() {
//Intent to pick image
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, IMAGE_PICK_CODE)
}
companion object {
//image pick code
private val IMAGE_PICK_CODE = 1000
//Permission code
private val PERMISSION_CODE = 1001
}
//handle requested permission result
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
when (requestCode) {
PERMISSION_CODE -> {
if (grantResults.size > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED
) {
//permission from popup granted
Toast.makeText(this, "Permission from popup granted", Toast.LENGTH_SHORT).show()
pickImageFromGallery()
} else {
//permission from popup denied
Toast.makeText(this, "Permission from popup denied", Toast.LENGTH_SHORT).show()
}
}
}
}
//handle result of picked image
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && requestCode == IMAGE_PICK_CODE && data != null) {
Picasso.get()
.load(data.data)
.fit()
.centerCrop()
.into(select_photo_imageView_register)
select_photo_textView_register.text = ""
}
}
private fun performRegister() {
val email = email_editText_register.text.toString()
val password = password_editText_register.text.toString()
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(this, "Please check email/password", Toast.LENGTH_SHORT).show()
return
}
Log.d("RegisterActivity", "Email: $email")
Log.d("RegisterActivity", "Password: $password")
//Firebase Auth
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
.addOnCompleteListener {
if (!it.isSuccessful) return#addOnCompleteListener
// else if successful
val uid = it.result?.user?.uid
Log.d("RegisterActivity", "Successfully created user with uid: $uid")
// uploadImageToFirebase()
}
.addOnFailureListener {
Log.d("RegisterActivity", "Failed to create user: ${it.message}")
Toast.makeText(this, "Failed to create user: ${it.message}", Toast.LENGTH_SHORT)
.show()
}
}
}
I use the emulator which defined as pixel 2, and use the image is from the gallery and taken by the emulator. The permission part works fine, but after I selected the image, there is no image set in the imageView. I have already tried to search online and adjusted my original code, such as change setImageURI to ImageDecode to create bitmap. I am a new bee on kotlin, so could you help me?
Here is my xml file and code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PostActivity">
<include
android:id="#+id/tool_bar"
layout="#layout/toolbar"/>
<EditText
android:id="#+id/text_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/image_button"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="100dp"
android:layout_marginRight="20dp"
android:background="#drawable/input_outline"
android:padding="15dp"
android:hint="#string/post_title"/>
<EditText
android:id="#+id/text_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/text_title"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:layout_marginRight="20dp"
android:background="#drawable/input_outline"
android:padding="15dp"
android:ems="10"
android:gravity="start|top"
android:inputType="textMultiLine"
android:hint="#string/post_description"/>
<Button
android:id="#+id/button_submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/colorPrimary"
android:text="#string/post_submit" />
<ImageView
android:id="#+id/image_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tool_bar"
android:layout_marginTop="50dp"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
app:srcCompat="#mipmap/add_btn" />
</RelativeLayout>
class PostActivity : AppCompatActivity() {
private var imageButton: ImageView?= null
// private val GALLERY_REQUEST = 1
companion object {
private val PERMISSION_CODE = 1000
private val IMAGE_PICK_CODE = 1001
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_post)
setSupportActionBar(findViewById(R.id.tool_bar))
imageButton = findViewById<ImageView>(R.id.image_button)
imageButton!!.setOnClickListener {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
var permissions= arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE)
requestPermissions(permissions, PERMISSION_CODE)
} else {
pickImageFromGallery()
}
} else {
pickImageFromGallery()
}
}
}
private fun pickImageFromGallery() {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, IMAGE_PICK_CODE)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
PERMISSION_CODE -> {
if (grantResults.isNotEmpty() && grantResults[0] ==PackageManager.PERMISSION_GRANTED) {
pickImageFromGallery()
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
}
}
}
}
#RequiresApi(Build.VERSION_CODES.P)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == IMAGE_PICK_CODE && requestCode== Activity.RESULT_OK) {
// imageButton?.setImageURI(data?.data)
if (data != null) {
val contentURI = data.data
try{
val source = ImageDecoder.createSource(this.contentResolver, contentURI!!)
val bitmap = ImageDecoder.decodeBitmap(source)
imageButton?.setImageBitmap(bitmap)
} catch(e: IOException) {
e.printStackTrace()
Toast.makeText(this, "Failed", Toast.LENGTH_SHORT).show()
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.post_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == R.id.action_setting) {
val intent = Intent(this, SettingActivity::class.java)
startActivity(intent)
}
return super.onOptionsItemSelected(item)
}
}
Hi Stack Overflow team,
Following is the java code of PhotoEditor Android app for capturing image and saving the image in the phone
Following is the MainActivity.java file:
package com.example.photoeditor;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import com.adobe.creativesdk.aviary.AdobeImageIntent;
public class MainActivity extends AppCompatActivity {
public static final String IMAGE_URI = "IMAGE_URI_KEY";
private static final String TAG = "MainActivity";
private static final int IMAGE_EDITOR_RESULT = 1;
private ImageView mEditedImageView;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditedImageView = (ImageView) findViewById(R.id.edited_image_view);
Bundle extras = getIntent().getExtras();
if (extras != null) {
Uri imageUri = Uri.parse(getIntent().getExtras().getString(IMAGE_URI));
Intent imageEditorIntent = new AdobeImageIntent.Builder(this).setData(imageUri).build();
startActivityForResult(imageEditorIntent, IMAGE_EDITOR_RESULT);
finish(); // Comment this out to receive edited image
}
}
// Do something with the edited image
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case IMAGE_EDITOR_RESULT:
Uri editedImageUri = data.getParcelableExtra(AdobeImageIntent.EXTRA_OUTPUT_URI);
Log.d(TAG, "editedImageUri: " + editedImageUri.toString());
Bundle extra = data.getExtras();
if (extra != null) {
boolean changed = extra.getBoolean(AdobeImageIntent.EXTRA_OUT_BITMAP_CHANGED);
Log.d(TAG, "Image edited: " + changed);
if (changed) {
mEditedImageView.setImageURI(editedImageUri);
}
}
break;
default:
throw new IllegalArgumentException("Unexpected request code");
}
}
}
public static Intent getIntent(Context context, Bundle bundle) {
Intent intent = new Intent(context, MainActivity.class);
if (bundle != null) {
intent.putExtras(bundle);
}
return intent;
}
}
Following is the HomeActivity.java file:
package com.example.photoeditor;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Objects;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
public class HomeActivity extends AppCompatActivity {
private static final String TAG = "HomeActivity";
private static final int GALLERY_RESULT = 1;
private static final int CAMERA_RESULT = 2;
private static final String FILE_PROVIDER_AUTHORITY = "com.example.photoeditor";
private static final int CAMERA_PERMISSION_REQ_CODE = 1001;
private static final int STORAGE_PERMISSION_REQ_CODE = 1002;
private String mCapturedImagePath;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
public void openCamera(View view) {
// check for camera permission if not granted before
if (ContextCompat.checkSelfPermission(this, CAMERA) != PERMISSION_GRANTED) {
String[] cameraPermission = { CAMERA };
ActivityCompat.requestPermissions(this, cameraPermission, CAMERA_PERMISSION_REQ_CODE);
} else {
dispatchImageCaptureIntent();
}
}
public void openGallery(View view) {
// check for storage permission if not granted before
if (ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {
String[] storagePermissions = { READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE };
ActivityCompat.requestPermissions(this, storagePermissions, STORAGE_PERMISSION_REQ_CODE);
} else {
dispatchGalleryIntent();
}
}
private void dispatchGalleryIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY_RESULT);
}
private void dispatchImageCaptureIntent() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile != null) {
Uri photoFileUri = FileProvider.getUriForFile(this, FILE_PROVIDER_AUTHORITY, photoFile);
Log.d(TAG, "dispatchImageCaptureIntent:photoFileUri: " + photoFile.toString());
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoFileUri);
startActivityForResult(cameraIntent, CAMERA_RESULT);
}
}
}
#Override public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case CAMERA_PERMISSION_REQ_CODE:
if (grantResults[0] == PERMISSION_GRANTED) {
dispatchImageCaptureIntent();
} else {
Toast.makeText(this, "Required camera permission not granted", Toast.LENGTH_SHORT).show();
}
break;
case STORAGE_PERMISSION_REQ_CODE:
if (grantResults[0] == PERMISSION_GRANTED) {
dispatchGalleryIntent();
} else {
Toast.makeText(this, "Required storage permission not granted", Toast.LENGTH_SHORT)
.show();
}
break;
default:
throw new IllegalArgumentException("Unexpected request code");
}
}
private File createImageFile() throws IOException {
String timeStamp = DateFormat.getDateTimeInstance().format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
mCapturedImagePath = image.getAbsolutePath();
return image;
}
private Bundle uriToBundle(Uri imageUri) {
Bundle bundle = new Bundle();
bundle.putString(MainActivity.IMAGE_URI, imageUri.toString());
return bundle;
}
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == GALLERY_RESULT) {
Uri imageUri = data.getData();
startActivity(MainActivity.getIntent(this, uriToBundle(Objects.requireNonNull(imageUri))));
} else if (requestCode == CAMERA_RESULT) {
File imageFile = new File(mCapturedImagePath);
Uri imageUri = Uri.fromFile(imageFile);
startActivity(MainActivity.getIntent(this, uriToBundle(imageUri)));
}
} else {
Toast.makeText(this, "Image not loaded.", Toast.LENGTH_SHORT).show();
}
}
public static Intent getIntent(Context context) {
return new Intent(context, HomeActivity.class);
}
}
Following is the activity_home XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.photoeditor.HomeActivity">
<ImageView
android:id="#+id/home_background"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_centerInParent="true"
android:contentDescription="#string/astronaut_content_desc"
android:scaleType="centerCrop"
android:src="#drawable/picture"/>
<LinearLayout
android:id="#+id/title_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="75dp"
android:gravity="center"
tools:ignore="UseCompoundDrawables">
<ImageView
android:id="#+id/home_logo"
android:layout_width="#dimen/logo_width"
android:layout_height="#dimen/logo_height"
android:contentDescription="#string/app_logo_content_desc"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:textColor="#color/whitePrimary"
android:textSize="50sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#id/title_home"
android:layout_centerHorizontal="true"
android:layout_marginBottom="25dp"
android:gravity="bottom">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="65dp">
<ImageView
android:id="#+id/camera_button_image"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerHorizontal="true"
android:contentDescription="#string/camera_button_content_desc"
android:onClick="openCamera"
android:src="#drawable/ic_camera_alt_white"/>
<TextView
android:id="#+id/camera_button_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/camera_button_image"
android:layout_marginTop="7dp"
android:onClick="openCamera"
android:text="#string/camera_button_text"
android:textColor="#color/whitePrimary"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/gallery_button_image"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerHorizontal="true"
android:contentDescription="#string/gallery_button_content_desc"
android:onClick="openGallery"
android:src="#drawable/ic_phone_android_white"/>
<TextView
android:id="#+id/gallery_button_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/gallery_button_image"
android:layout_marginTop="7dp"
android:onClick="openGallery"
android:text="#string/gallery_button_text"
android:textColor="#color/whitePrimary"/>
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
Following is the activity_main XML file:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
tools:context="com.example.photoeditor.MainActivity">
<ImageView
android:id="#+id/edited_image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:contentDescription="#string/edited_image_content_desc"/>
</LinearLayout>
Issue is after capturing the image and then after editing the photo from the app and then when the image has to be saved, I see that image is not getting saved in the phone
When I see the Logcat in Android Studio, I saw this warning:
2018-10-27 23:59:57.250 2437-3574/com.example.photoeditor D/skia-encoders: [time] JPEG Decode 951
2018-10-27 23:59:57.250 2437-3574/com.example.photoeditor V/moahd-jni: decode time: 952
2018-10-27 23:59:57.250 2437-3574/com.example.photoeditor V/moahd-jni: bitmap.size: 5184x3880
2018-10-27 23:59:57.250 2437-3574/com.example.photoeditor I/moahd-jni: resize(15)
2018-10-27 23:59:57.250 2437-3574/com.example.photoeditor V/moahd-jni: bitmap MP: 20, max MP: 15
2018-10-27 23:59:57.250 2437-3574/com.example.photoeditor W/moahd-jni: Image must be resized! 20MP -> 15MP
2018-10-27 23:59:57.250 2437-3574/com.example.photoeditor V/moahd-jni: target: 15MP = (4477x3351), max size: 4477
2018-10-27 23:59:57.250 2437-3574/com.example.photoeditor V/moahd-jni: original: 20MP = (5184x3880)
2018-10-27 23:59:57.250 2437-3574/com.example.photoeditor V/moahd-jni: maxWidth: 4477, maxHeight: 3351
So saving issue is only if the image is captured when the camera size of the phone is more than 15Megapixel.
Can anyone please help with the possible code solution?
Thanks in advance
Use this code to resize and save:
Bitmap image = (Bitmap) "your image";
image = Bitmap.createScaledBitmap(photo, 100, 100, false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "name.jpg");
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
60 indicates the quality of compression: 0 is maximum compression low quality. 100 is least compression highest quality