Android pick image from gallery - android

I have selected an image from the gallery, now what I want is when the user reopens the app, the image is there in the ImageView, Please suggest me something, here is my code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
imgView = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.profileimg);
SharedPreferences.Editor editor = getSharedPreferences(AppConstants.VERIFICATION, MODE_PRIVATE).edit();
editor.putString(AppConstants.PROFILEIMAGE, imgDecodableString);
editor.commit();
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}

Try this code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
imgView = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.profileimg);
Bitmap bmap = imgView.getDrawingCache();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmap.compress(Bitmap.CompressFormat.PNG, 90, bytes);
byte[]imagebytes=bytes.toByteArray();
String encodedImage = Base64.encodeToString(imagebytes, Base64.DEFAULT);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(ProfilePage.this);
SharedPreferences.Editor edit=shre.edit();
edit.putString("image_data",encodedImage);
edit.commit();
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
add this below code to get shared preference
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
String previouslyEncodedImage = shre.getString("image_data", "");
if( !previouslyEncodedImage.equalsIgnoreCase("") ){
byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
imgView.setImageBitmap(bitmap);
}

#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
// Do something with the bitmap
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
}

Use
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
InputStream inputStream = getContentResolver()
.openInputStream(data.getData());
File outFile = new File(getCacheDir(),"tempImage.png");
FileOutputStream fileOutputStream = new FileOutputStream(
outFile);
copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
Bitmap bm = BitmapFactory.decodeStream(inputStream);
imgView = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.profileimg);
imgView.setImageBitmap(bm);
SharedPreferences.Editor editor = getSharedPreferences(AppConstants.VERIFICATION, MODE_PRIVATE).edit();
editor.putString(AppConstants.PROFILEIMAGE, outFile.getAbsolutePath());
editor.commit();
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
public static void copyStream(InputStream input, OutputStream output)
throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}

Related

file not creating in android internal storage

This is function for saving images. I am trying to save the image name (from gallery) to a file (preferably csv file). but the android is not creating the file. need help in creating the file in android internal storage.
public void saveImage(String imagePath){
String[] arrOfStr = imagePath.split("/"); //splitting full image path by / to only get the image name e.g 00001.jpg
String imageName = null;
for (String a : arrOfStr)
imageName = a; // imageName only contains the imageName i.e 00001.jpg
String filename = "test_ids.txt";
try {
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, filename);
FileWriter writer = new FileWriter(gpxfile);
writer.append(imageName);
writer.flush();
writer.close();
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Not Saved", Toast.LENGTH_SHORT).show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK && data != null) {
Bitmap selectedImage = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(selectedImage);
}
break;
case 1:
if (resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
if (selectedImage != null) {
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
saveImage(picturePath); // a function to save images
imageView.setImageURI(selectedImage);
cursor.close();
}
}
}
break;

Get the exact File Size of an Image from the selected image in gallery

This is my code for file chooser
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
then onActivityResult()
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
System.out.println(bitmap.getByteCount());
int w = bitmap.getWidth();
int h = bitmap.getHeight();
if (w!= 512 || h!= 512)
{
txvLogoError.setText("Invalid image dimensions. Please choose another.");
}
else
{
txvLogoError.setText("");
imbAppLogo.setPadding(10,10,10,10);
imbAppLogo.setImageBitmap(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
my question is, how can I get the exact file size of the image selected? I tried File.length() but the result is 0.
Try this .
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
int dataSize=0;
if (requestCode == 2 && resultCode == RESULT_OK)
{
Uri uri = data.getData();
String scheme = uri.getScheme();
System.out.println("Scheme type " + scheme);
if(scheme.equals(ContentResolver.SCHEME_CONTENT))
{
try {
InputStream fileInputStream=getApplicationContext().getContentResolver().openInputStream(uri);
dataSize = fileInputStream.available();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("File size in bytes"+dataSize);
}
else if(scheme.equals(ContentResolver.SCHEME_FILE))
{
String path = uri.getPath();
try {
f = new File(path);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("File size in bytes"+f.length());
}
}
}
try the following,
File f = new File(filePath.getPath());
long size = f.length();
Otherwise you can try
Cursor returnCursor = getContentResolver().query(filePath, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);

How do we check image size before inserting in imageview in android?

I have an app which contain a "imageview" and a "button" known as uploadImage. when i click uploadimage it is opening a a chooser option from where user can choose image and set it in imageview. Problem is that before setting image in image view i want to check whether image size is not more that 200 kb if found then show toast message otheriwse proceed further.
code:-
private void showFileChooser() {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
// Set the Image in ImageView after decoding the String
m_UploadImage.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
You can check the image size using the following Code:
Bitmap bitImage = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);// For example I took ic_launcher
Bitmap bitmap = bitImage;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
long sizeOfImage = imageInByte.length; //Image size
Your Code :
private void showFileChooser() {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
// Set the Image in ImageView after decoding the String
Bitmap bitImage = BitmapFactory.decodeFile(imgDecodableString);
Bitmap bitmap = bitImage;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
long sizeOfImage = imageInByte.length; //Image size
//Code to check image size greater than 20KB
if(sizeofImage/1024 > 200){
Toast.makeText(this, "Image size more than 200KB", Toast.LENGTH_LONG)
}else{
m_UploadImage.setImageBitmap(bitImage);
}
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
Or you can try this way ,
First you get the Bitmap attached on the ImageView:
using this :
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
In your code :
private void showFileChooser() {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
// Set the Image in ImageView after decoding the String
m_UploadImage.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
//Get the Bitmap in your ImageView
Bitmap bitmap = ((BitmapDrawable)m_UploadImage.getDrawable()).getBitmap();
// Then check the Image size
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
long lengthbmp = imageInByte.length;
Toast.makeText(this, "Length of the Image :" + lengthbmp,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
Better you create a an another class and write this public method in that class because in future you can use this class.
public class UtilClassName{
public static int getFileSize(Uri imageUri,Activity activity){
int kb_size=0;
try {
InputStream is=activity.getContentResolver().openInputStream(imageUri);
int byte_size=is.available();
int kb_size=byte_size/1024;
}
catch (Exception e){
// here you can handle exception here
}
return kb_size;
}
}
In your code use this logic
if(UtilClassName.getFileSize(selectedImage,this)<=200){
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
// Set the Image in ImageView after decoding the String
m_UploadImage.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
}
else{
//show a warning to the user
}
Try this method and if you are facing any issue let me know. I had faced this problem before and i created this method for a file compressor class. I hope you will get solution.

Captured image does not display on ImageView

In my Activity A, there is an ImageView and a Button. When the button is clicked, it goes to activeTakePhoto(). The imgUri gets displayed but nothing is displayed in my ImageView.
private void activeTakePhoto() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver()
.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
takePictureIntent
.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE &&
resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver()
.query(selectedImage, filePathColumn, null, null,
null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
}
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE &&
resultCode == RESULT_OK) {
File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
ImageView imgView=(ImageView)findViewById(R.id.imageView);
Uri imgUri=Uri.fromFile(picture);
imgView.setImageURI(imgUri);
Toast.makeText(getApplication(),imgUri+"",Toast.LENGTH_LONG).show();
}
}
}
You can try this code,it may help:
#Override
public void onClick(View v) {
if (v == imgCamera) {
Toast.makeText(getApplicationContext(), "open camera", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
}//on click
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("RESULT CODE", "--" + resultCode);
if (resultCode == RESULT_OK) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
//to generate random file name
String fileName = "tempimg.jpg";
try {
Bitmap photo = (Bitmap) data.getExtras().get("data");
//captured image set in imageview
imageView.setImageBitmap(photo);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
in activeTakePhoto
Replace
String fileName = "temp.jpg";
with
fileName=Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp.jpg"

Can't upload image capture from camera android

I'm trying to write a small code that allows me to send picture directly after taking it from the camera, i want to send pict from capture in camera but never sucess, i'm always get message "Something went wrong"
There is the code
public void loadImagefromGallery(View view) {
CharSequence colors[] = new CharSequence[] {"Galery", "Foto"};
AlertDialog.Builder builder = new AlertDialog.Builder(UserProfileActivity.this);
builder.setTitle("Pilih");
builder.setItems(colors, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
} else if (which == 1) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_REQUEST);
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if(requestCode == CAMERA_REQUEST){
Bitmap photo = (Bitmap) data.getExtras().get("data");
RoundedImageViewUtil imgView = (RoundedImageViewUtil) findViewById(R.id.profile);
imgView.setImageBitmap(photo);
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgPath));
String fileNameSegments[] = imgPath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
params.put("filename", fileName);
} else if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
RoundedImageViewUtil imgView = (RoundedImageViewUtil) findViewById(R.id.profile);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgPath));
String fileNameSegments[] = imgPath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
params.put("filename", fileName);
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
Intead of
Bitmap photo = (Bitmap) data.getExtras().get("data");
try
Uri imageUri = (Uri)data.getData();
and then from uri get your image bitmap.

Categories

Resources