Resgistering photos issues in android programming - java

I am implementing an android app using camera to take pictures then registering it in External_storage\Android\data\com.abc.projectname.bf . But after openning the camera , even if i don't capture , an image file is registered in the directory . How can i solve that , here is the code :
public void onCapturePhoto(String fileName){
//Intent to take photos
File storageDirectory = requireActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try {
Log.d("#picName",fileName);
File imageFile = File.createTempFile(fileName,".jpg",storageDirectory);
currentPhotoPath = imageFile.getAbsolutePath();
Uri imageUri= FileProvider.getUriForFile(requireActivity(),"com.ticanalyse.mheath.bf",imageFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(intent,1);
Log.d("#image_length is ",String.valueOf(imageFile.length()));
} catch (IOException e) {
e.printStackTrace();
}
}
//
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
// imageView.setImageBitmap(imageBitmap);
// File f = new File(currentPhotoPath);
//// Uri contentUri = Uri.fromFile(f);
// Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath);
// //Convert bitmap to byteArray
// ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
// byte[] byteArray = byteArrayOutputStream .toByteArray();
// //Then convert to base64
// encodedImage= Base64.encodeToString(byteArray, Base64.DEFAULT);
// Log.d("#base64",encodedImage);
// setPic();
}
}

First of all, have the imageFile object from this line:
File imageFile = File.createTempFile(fileName,".jpg",storageDirectory);
...declared as a global in the Activity like this...
public class XYZActivity extends AppCompatActivity {
private File imageFile;
//onCreate(), onCapturePhoto(), etc methods
}
Then in onCapturePhoto():
imageFile = File.createTempFile(fileName,".jpg",storageDirectory);
Now in the onActivityResult(), if you ensure that no image was taken/clicked, you could try deleting the temporary file like this:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
//Your stuff...
}
else {
//No photo was taken or clicked...
//Thus, deleting the temporary file...
if (file.exists()) {
if (file.delete()) {
Log.i("Process", "Deletion DONE!");
}
}
}
}
If I interpreted any part of problem in a undesirable way, please let me know.

Related

android take image from phone album and store it in sqlite database

i'm making an app where the user can choose images from the phone's album and store it into a table in sqlite database, i have seen many posts here about this issue but couldn't understand the solutions (neither did they work for me), in my activity i have an imageview which when clicked will open the album and allow the user to choose an image and also i have a button which when clicked will store the image in sqlite database, i'm just able to choose the image but after that i'm stuck, i got to this method in my code:
public void getImage(View view) throws IOException {
ImageView v=(ImageView)view;
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent,1);
}
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContext().getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
image.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
now what should i do after this to store the image in the db?
If you are sure about the images will not be removed from internal storage, you can save the image path. If want to save the image data, you can do the following.
for selecting image
private void selectImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, IMAGE_REQ);
}
In onActivityResult, from Intent data ...
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_REQ && resultCode == Activity.RESULT_OK && data != null) {
Uri path = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), path);
Bitmap.createScaledBitmap(bitmap, 150, 150, true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
get byte[] from bitmap
public static byte[] getByteArrayFromBitmap(Bitmap bitmap) {
if(bitmap == null) return null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
then save the byte[] as blob in sqlite
for getting the images as bitmap
public static Bitmap getBitmapFromByteArray(byte[] blob){
if(blob == null) return null;
Bitmap bitmap = BitmapFactory.decodeByteArray(blob, 0, blob.length);
return bitmap;
}

compressing selected image file/taken from camera

trying to let users add profile pictures, but I want to compress the image file before sending it to the server.
How can i compress the:
File imageFile = new File(resultUri.getPath());
Tried and searched but couldn't get to work
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
btnConfirm.setVisibility(View.VISIBLE);
btnConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File imageFile = new File(resultUri.getPath());
progressDialog.show();
AndroidNetworking.upload("https://myweb.com/uploadImg.php")
.addMultipartFile("image", imageFile)
Would love to get some advice, Thanks in advance.
Check this
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(
selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
try {
stream.close();
stream = null;
} catch (IOException e) {
e.printStackTrace();
}

Storing image in SharedPreferences

mHomePage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_CODE);
}
});
mHomePage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD);
}
});
return rootView;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// When an Image is picked
if (requestCode == RESULT_LOAD && resultCode == RESULT_OK) {
Uri resultUri = data.getData();
CropImage.activity(resultUri)
.start(getActivity());
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
Uri uri = result.getUri();
Bitmap realImage = BitmapFactory.decodeStream(uri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
realImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor edit=shre.edit();
edit.putString("image_data",encodedImage);
edit.commit();
}
Trying to store image in sharedpreference by encoding but I'm new to this and not able to figure it out. I saw some questions related to this problem but those aren't clear. Can someone help me out on how to store path/image in SharedPreferences?
Code isn't even compiling as I have put a uri in inout stream in .decodeStream().
The Uri points to the path where the image is stored, so first you would have to read it with InputStream.
This code will fix the compilation error. As a side-node, use edit.apply() instead of edit.commit().
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
try
{
InputStream ims = getContentResolver().openInputStream(uri);
Bitmap realImage = BitmapFactory.decodeStream(uri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
realImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit=shre.edit();
edit.putString("image_data",encodedImage);
//edit.commit();
edit.apply();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
However, I don't really see a point in storing an image in SharedPreferences? It's not really meant for that. Why don't you use save the file in context.getFilesDir() and read it from there when you need it? It's better than encoding/decoding it.

Get base64 String from Image URI

I have content:// URI of an image and I want to convert it to base64. I don't know how to do this.
Here is my code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==123 && resultCode==RESULT_OK) {
Uri selectedfile = data.getData(); //The uri with the location of the file
if (selectedfile != null) {
Log.e("image", selectedfile.toString());
}
}
}
You can do it by using 2 steps.
1- URI to Bitmap conversion:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==123 && resultCode==RESULT_OK) {
Uri selectedfile = data.getData(); //The uri with the location of the file
if (selectedfile != null) {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedfile);
}
}
}
2- Bitmap to Base64 String conversion:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
byte[] byteArray = outputStream.toByteArray();
String encodedString = Base64.encodeToString(byteArray, Base64.DEFAULT);
As a result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==123 && resultCode==RESULT_OK) {
Uri selectedfile = data.getData(); //The uri with the location of the file
if (selectedfile != null) {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedfile);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
byte[] byteArray = outputStream.toByteArray();
//Use your Base64 String as you wish
String encodedString = Base64.encodeToString(byteArray, Base64.DEFAULT);
}
}
}

How to open Gallery to pick an image?

I am looking for a way to open onClick the gallery to pick an Picture.
I want to use that local "uploaded" picture in a listview of pictures.
Can someone help and explain me how to do that. I am a beginner in Android Developing.
public void pickImage() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PICK_PHOTO_FOR_AVATAR);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_PHOTO_FOR_AVATAR && resultCode == Activity.RESULT_OK) {
if (data == null) {
//Display an error
return;
}
InputStream inputStream = context.getContentResolver().openInputStream(data.getData());
//Now you can do whatever you want with your inpustream, save it as file, upload to a server, decode a bitmap...
}
}
Here is a code i used in my app
Intent pickImageIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickImageIntent, PICKIMAGE_REQUESTCODE);
And at the onActivity result method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICKIMAGE_REQUESTCODE) {
if (resultCode == RESULT_OK) {
Uri imageUri = data.getData();
InputStream inputStream = null;
try {
inputStream = getContentResolver().openInputStream(imageUri);
bitmap = BitmapFactory.decodeStream(inputStream);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "onActivityResult: error closing InputStream during reading image from the phone external storage");
}
}
}

Categories