Share photo on Facebook Android SDK - android

I'm trying to share a photo on Facebook with Android SDK.
The problem is that my Bitmap image is null. This is my code:
public void sharePhoto(View view) {
if (Session.getInstance().getUserFace().getBestphoto() == null) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
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();
Log.d("picture path", picturePath);
BitmapFactory.Options options = new BitmapFactory.Options();
try {
Bitmap image = BitmapFactory.decodeFile(picturePath, options);
uploadPhoto(image);
} catch (OutOfMemoryError e) {
try {
options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap image = BitmapFactory.decodeFile(picturePath, options);
uploadPhoto(image);
} catch (Exception ex) {
Log.e("EXCEPTION", ex.toString());
}
}
}
}
private void uploadPhoto(Bitmap image) {
Log.d("Image", "" + image);
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(image)
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
ShareDialog.show(MainActivity.this, content);
}

You can try getting the bitmap from InputStream instead. Use this,
BitmapFactory.decodeStream(resolver.openInputStream(uri), null, options);
where resolver is your ContentResolver and uri is returned by data.getData();
You won't need to query the database, unless you wanna check for any FileNotFoundException.

File file = new File(picturePath);
Uri imageUri = Uri.fromFile(file.getAbsoluteFile());
try {
Bitmap image = BitmapFactory.decodeStream(mContext.getContentResolver().openInputStream(imageUri));
uploadPhoto(image);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Your "picturePath" cursor from MediaStore, it maybe like this /storage/emulated/0/DCIM/Camera/IMG20200513xx.jpg.
You can try to changing path to content URI (file:///storage/emulated/0/DCIM/Camera/IMG20200513xx.jpg).
Use content provider's getContentResolver() to open your image. Then decode image to Bitmap.

Related

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.

How do I save image in imageview?

My app lets you pick an image from gallery and shows it in imageview, but when you close the activity and open it again the image is not there anymore.
private final static int RESULT_LOAD_IMAGE = 1;
public void getpic(View view) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
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 selectedimage = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imageButton3);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageBitmap(BitmapFactory.decodeFile(selectedimage));
}
}
How can I save the picked image?
You can get Bitmap from ImageView to save it:
imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
Use Glide for loading image
add below dependencies in build.gradle(app)
compile 'com.github.bumptech.glide:glide:4.2.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.2.0'
add below code inside your onActivityResult
Glide
.with(mContext)
.load(selectedimage)
.centerCrop()
.placeholder(R.color.black)
.crossFade()
.into(imageView);
For more details refer
https://github.com/bumptech/glide
http://en.proft.me/2016/09/12/load-process-and-cache-image-android-using-glide/
Glide load local image by Uri.

How to get address from gallery in android

I write this code and my code choose one picture from gallery and get data from it but I dont konw how to get image address from Inputstrem or data and store it?
public void loadPic()
{
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1)
{
try {
Uri selectedImage=data.getData();
InputStream inputStream = getContentResolver().openInputStream(selectedImage);
listItems.add(inputStream.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Read filename name like below, use it accordingly.
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);
File f = new File(picturePath);
String imageName = f.getName();
Sometimes, you can't get a file from the picture you choose.
It's because the choosen one came from Google+, Drive, Dropbox or any other provider.
The best solution is to ask the system to pick a content via Intent.ACTION_GET_CONTENT and get the result with a content provider.
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...
}
}
I'm not sure if this is exactly what you want, but you can get the image like this:
Uri selectedImage = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImage);
Once you have the Bitmap, you can see here on how to store it.
EDIT: Try this
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();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Taken from here.

Android Camera Intent crashes with Android L

My app is working properly on all api till Kitkat but it's not working in lollipop. The moment i clicks for capturing a photo using camera in my app, it crashes.
cam.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
This is my onActivityResult()
case CAMERA_REQUEST: {
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();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
options.inSampleSize = calculateInSampleSize(options,200,100);//512 and 256 whatever you want as scale
options.inJustDecodeBounds = false;
Bitmap yourSelectedImage = BitmapFactory.decodeFile(picturePath,options);
File pngDir = new File(Environment.getExternalStorageDirectory(),"PicUploadTemp");
if (!pngDir.exists()) {
pngDir.mkdirs();
}
File pngfile = new File(pngDir,"texture1.jpg");
FileOutputStream fOut;
try {
fOut = new FileOutputStream(pngfile);
yourSelectedImage.compress(Bitmap.CompressFormat.JPEG, 50,fOut);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Drawable d = Drawable.createFromPath(pngfile.getPath().toString());
rlLayout.setBackground(d);
yourSelectedImage.recycle();
// resizedBitmap.recycle();
xfile = pngfile;
}
break;
I want to compress the image and this above code is working amazingly for gingerbread, ICS , kitkat but not for Android L
I am getting null pointer Exception
Please suggest me some solution
Thanks in advance
Cannot really say anything about this without the logcat output, It may be becoming null in as a result of you using on of the deprecated method in the BitmapFacotry class.
Define these globally in your activity,
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
private static final int CAMERA_REQUEST = 1888;
in button click call your camera intent like this
startActivityForResult(cameraIntent, CAMERA_REQUEST);
make sure to use
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
use this to retrieve photo
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == getActivity().RESULT_OK) {
//get photo
Bitmap photo = (Bitmap) data.getExtras().get("data");
}

How to get preview of captured image through camera intent in android

Hi am capturing an image through camera intent it works good but my problem is that am not getting preview of that image
my requirement is very simple, after clicking of photo through camera it must ask me to SAVE or DISCARD this image if i press SAVE then it get save into sd card thats it...
here is my code
private void openCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
capturedFile = new File(Environment.getExternalStorageDirectory(),
"tmp_nookster_profilepic"
+ String.valueOf(System.currentTimeMillis()) + ".jpg");
mImageCaptureUri = Uri.fromFile(capturedFile);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA_NO_CROP);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA_NO_CROP: {
iu.SaveCapturedImage(BitmapFactory.decodeFile(capturedFile
.getAbsolutePath()));
try {
if (capturedFile.exists())
capturedFile.delete();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
break;
here "iu" is object of ImageUtility class and "SaveCapturedImage" is method to store that captured image in SdCard
You can get a preview of the captured File as this:
Bitmap getPreview(File image) {
final int THUMBNAIL_SIZE = 72;
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getPath(), bounds);
if ((bounds.outWidth == -1) || (bounds.outHeight == -1))
return null;
int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
: bounds.outWidth;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = originalSize / THUMBNAIL_SIZE;
return BitmapFactory.decodeFile(image.getPath(), opts);
}
then you can show the Bitmap in an ImageView and present the user with Save/Delete buttons.
You have to remove line from your code.
if (resultCode != RESULT_OK)
return;
Use following code :
if (resultCode == RESULT_OK)
{
try
{
Bitmap bitmap=null;
String imageId = convertImageUriToFile(imageUri,AddRecipes.this);
bitmap = BitmapFactory.decodeFile(imageId);
}}
public static String convertImageUriToFile (Uri contentUri, Activity activity)
{
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader cursorLoader = new CursorLoader(activity.getApplicationContext(),contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

Categories

Resources