My code is working perfectly fine in API level <= 19 but in greater version I am getting bitmap null.
public void SelectImage() {
final CharSequence[] items = {"Camera", "Gallery", "Cancel"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.add_image);
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if (items[i].equals("Camera")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(mainActivity.getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_CAMERA);
}
} else if (items[i].equals("Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, SELECT_FILE);
} else if (items[i].equals("Cancel")) {
dialog.dismiss();
}
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
place = PlacePicker.getPlace(data, mainActivity);
etAddress1.setText(place.getAddress());
}
} else if (resultCode == Activity.RESULT_OK && data != null) {
Glide.with(this).load(data.getData()).into(ivprofile);
Bitmap bm = null;
try {
bm = MediaStore.Images.Media.getBitmap(mainActivity.getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 50, baos);
byte[] b = baos.toByteArray();
base64img = Base64.encodeToString(b, Base64.NO_WRAP);
}
}
Here my bm is null why this happening am i using the older code version or is there anything else.. Thanks in advance.
Actually, there is a library which works with every phone and every android version. If you need to solve you problem here is an answer. EasyImage did the job!
do not forget to handle permissions api 23 and up !
Related
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;
}
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.
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 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");
}
}
}
Hey, I am currently working on a live wallpaper and I allow the user to select an image which will go behind my effects.
Currently I have:
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.putExtra("crop", "true");
startActivityForResult(i, 1);
And slightly under that:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
Log.d("IMAGE SEL", "" + selectedImage);
// TODO Do something with the select image URI
SharedPreferences customSharedPreference = getSharedPreferences("imagePref", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference.edit();
Log.d("HO", "" + selectedImage);
editor.putString("imagePref", getRealPathFromURI(selectedImage));
Log.d("IMAGE SEL", getRealPathFromURI(selectedImage));
editor.commit();
}
}
When my code is ran, Logcat tells me that selectedImage is null. If I comment out the
i.putExtra("crop", "true"):
Logcat does not give me the null pointer exception, and I am able to do what I want with the image. So, what is the problem here? Does any one have any idea how I can fix this? Thanks, for your time.
I have also faced this problem .You can try with this code. Its working fine for me
private static final String TEMP_PHOTO_FILE = "temporary_holder.jpg";
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, REQ_CODE_PICK_IMAGE);
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
private File getTempFile() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(),TEMP_PHOTO_FILE);
try {
file.createNewFile();
} catch (IOException e) {}
return file;
} else {
return null;
}
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case REQ_CODE_PICK_IMAGE:
if (resultCode == RESULT_OK) {
if (imageReturnedIntent!=null) {
File tempFile = getTempFile();
String filePath= Environment.getExternalStorageDirectory()
+"/"+TEMP_PHOTO_FILE;
System.out.println("path "+filePath);
Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
_image = (ImageView) findViewById(R.id.image);
_image.setImageBitmap(selectedImage );
if (tempFile.exists()) tempFile.delete();
}
}
}
}
You don't need a Temp file:
protected static final int REQ_CODE_PICK_IMAGE = 1;
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra("return-data", true);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, REQ_CODE_PICK_IMAGE);
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case REQ_CODE_PICK_IMAGE:
if (resultCode == RESULT_OK) {
if (imageReturnedIntent!=null) {
Bundle extras = imageReturnedIntent.getExtras();
Bitmap selectedBitmap = extras.getParcelable("data");
imageR = (ImageView) findViewById(R.id.image);
imageR.setImageBitmap(selectedBitmap);
}
}
}
}
This code good with "beginners" ^^
private Bitmap FixBitmap;
Bitmap thePicBitmap;
String ImagePath = "image_path";
String ImagePath_1;
private static final String TEMP_PHOTO_FILE = "temporary_holder.jpg";
private static final int REQ_CODE_PICK_IMAGE = 0;
#Override
public void onClick(View view) {
try {
//intent = new Intent();
// intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//intent.setAction(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra("scale", true);
photoPickerIntent.putExtra("aspectX", 1);
photoPickerIntent.putExtra("aspectY", 1);
// indicate output X and Y
photoPickerIntent.putExtra("outputX", 150);
photoPickerIntent.putExtra("outputY", 100);
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, REQ_CODE_PICK_IMAGE);
} catch (Exception e) {
// Toast.makeText(getApplicationContext(), R.string.imageException, Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
Toast toast = Toast.makeText(Upload_image_text.this, "This device doesn't support the crop action!",
Toast.LENGTH_SHORT);
toast.show();
}
}
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
private File getTempFile() {
if (isSDCARDMounted()) {
File f = new File(Environment.getExternalStorageDirectory(),TEMP_PHOTO_FILE);
try {
f.createNewFile();
} catch (IOException e) {
}
return f;
} else {
return null;
}
}
private boolean isSDCARDMounted(){
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED))
return true;
return false;
}
});
=======================
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case REQ_CODE_PICK_IMAGE:
if (resultCode == RESULT_OK) {
if (imageReturnedIntent!=null){
// File tempFile = getTempFile();
ImagePath_1 = Environment.getExternalStorageDirectory()
+ "/temporary_holder.jpg";
System.out.println("path "+ImagePath_1);
FixBitmap = BitmapFactory.decodeFile(ImagePath_1);
ShowSelectedImage = (ImageView)findViewById(R.id.imageView);
ShowSelectedImage.setImageBitmap(FixBitmap);
}
}
}
}
===============================
#Override
protected String doInBackground(Void... params) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
//options.outWidth = 50;
//options.outHeight = 50;
FixBitmap = BitmapFactory.decodeFile(ImagePath_1, options);
//FixBitmap = BitmapFactory.decodeResource(getResources(), R.id.imageView);
byteArrayOutputStream = new ByteArrayOutputStream();
FixBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); //compress to 50% of original image quality
byteArray = byteArrayOutputStream.toByteArray();
ConvertImage = Base64.encodeToString(byteArray, Base64.DEFAULT);