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.
Related
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.
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;
}
Button click to open camera, take picture and tried to convert that selected picture to base64 string but not working. please check below code.
private static final int CAMERA_PIC_REQUEST = 1337;
Button upload;
#Override
protected void onCreate(Bundle savedInstanceState) {
upload = findViewById(R.id.upload);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
Bitmap image = (Bitmap) data.getExtras().get("data");
ImageView imageview = (ImageView) findViewById(R.id.uploadimage);
imageview.setImageBitmap(image);
String directoryPath = Environment.getExternalStorageDirectory() + "/";
String filePath = directoryPath+Long.toHexString(System.currentTimeMillis())+".png";
File directory = new File(directoryPath);
if (!directory.exists()) {
directory.mkdirs();
}
System.out.print(filePath);
System.out.print(Uri.fromFile( new File(filePath) ));
File imageFile = new File(filePath);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image1 = stream.toByteArray();
String img_str = Base64.encodeToString(image1, 0);
}
I worked below code for convert static image into base64 string, but i want to take picture and convert to base64 string.
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), R.drawable.testimage);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.PNG, 100, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba,Base64.DEFAULT);
System.out.print(ba1);
Please follow this to get actual image.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
String imgString = toBase64(photo);
}
}
public String toBase64(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
return Base64.encodeToString(b, Base64.NO_WRAP);
}
What I understand is, you need to do two things with the taken picture:
Show the picture in imageView.
Convert the picture to base64 String.
To do these two things, you don't need to write the Picture to file at your own code. You have already the bitmap from the camera using the following code:
Bitmap pictureFromCamera = (Bitmap) data.getExtras().get("data");
Now just show it in the imageView using
imageView.setImageBitmap(pictureFromCamera)
To convert it to base64, just convert the pictureFromCamera to base64 like
String base64StringOfCameraPic = getBase64StringFromBitmap(pictureFromCamera , 100)
String getBase64StringFromBitmap(Bitmap bitmap, int quality)
{
if (bitmap == null || quality < 0)
{
return null;
} else
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, quality, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
}
}
User can capture or select a image from gallery. I would like to upload that image to server.
This is my code for camera -
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//String encode = ImageBase64.encode(i);
startActivityForResult(i, CAMERA_REQUEST);
}
});
And this is my code to select a image from gallery -
gallary.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent g = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(g, GALLARY_REQUEST);
}
});
Also, I am displaying that image with below code -
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) {
if(requestCode == CAMERA_REQUEST) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
uploaded_img.setImageBitmap(bitmap);
}
}
if(requestCode == GALLARY_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
uploaded_img.setImageURI(uri);
}
}
Now, I would like to convert this image to base64 and upload to server.
Here you go:
public static String convertToBase64(String path) {
Bitmap bm = BitmapFactory.decodeFile(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] byteArrayImage = baos.toByteArray();
String encodedImage = android.util.Base64.encodeToString(byteArrayImage, android.util.Base64.DEFAULT);
return encodedImage;
}
public static Bitmap decodeFromBase64ToBitmap(String encodedImage) {
byte[] decodedString = android.util.Base64.decode(encodedImage, android.util.Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
return decodedByte;
}
I've made it static in my project, so i don't have to create class instance.
I select image from gallery and take image through camera.The code is following:
ib2 = (ImageButton) findViewById(R.id.imageButton2);
ib2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
private static final int PICK_IMAGE = 150;
Uri imageUrl;
private void openGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestcode, int resultcode, Intent data) {
super.onActivityResult(requestcode, resultcode, data);
if (resultcode == RESULT_OK && requestcode == PICK_IMAGE) {
imageUrl = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUrl );
// Log.d(TAG, String.valueOf(bitmap));
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
// im.setImageURI(imageUrl);
}
if (requestcode == CAMERA_REQUEST && resultcode == RESULT_OK) {
Bitmap photo;
photo = (Bitmap) data.getExtras().get("data");
im.setImageBitmap(photo);//set image to Imageview
}
}
Then trying to convert this image into base 64 string. The code is following:
private String imageToString(){
Bitmap photo = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
Then send the data to another activity. The code is following:
Intent next = new Intent(MainActivity.this, EventAdding.class);
Bundle bn = new Bundle();
bn.putString("image", imageToString());
startActivity(next);
The problem is that I am unable to synchronize all those program. The converting image string data don't send perfectly to the next activity.Image data don't send. when I was trying to show the image, a blank image is shown. Please, inform me the correct code
you can send image from one activity to other activity using the following code..
Bitmap bitmap = youimage
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("image", bitmap);
startActivity(intent);
now get the image in the secondActivity like this.
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("image");
Then display bitmap in ImageView.
You can use the intent.getParcelableExtra(key) method