Bitmap Share Intent - android

I am trying to convert entire CardView into an Image and then I want to share it using different apps.
PROBLEM
cardView.setDrawingCacheEnabled(true);
cardView.measure(View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED));
cardView.layout(0,0, cardView.getMeasuredWidth(), cardView.getMeasuredHeight());
cardView.buildDrawingCache(true);
bitmap = Bitmap.createBitmap(cardView.getDrawingCache());
cardView.setDrawingCacheEnabled(false);
String path = MediaStore.Images.Media.insertImage(DetailedActivity.this.getContentResolver(),bitmap,"quote",null);
uri = Uri.parse(path);
Thing is I am getting cardview converted into bitmap but while getting uri from bitmap it is returning null path. so while converting Uri it is giving NULL POINTER EXCEPTION.
Below is the list of permissions I provided.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"
tools:ignore="ProtectedPermissions" />
CardView XML
If I give the CardView a defined hardcoded values for Height and Width of a CardView it is working but when I use
android:layout_width="match_parent"
android:layout_height="match_parent"
With the code shown above it is giving NULL_POINTER_EXCEPTION.
QUERIES
1. How can I make it work?
2. Is there any other way to do this?

So if I get it right, the URI path is stored in uri variable. The null error happens because you didn't initialise that uri string. You can do this:
String uri = new String() // -> if there is still an error here, replace String() with String(this) or String(activity_your_name.this)
Intent intent = new Intent(this, activity_output.class); // -> here you add the activity where you send the URI to
intent.putExtra("URI", uri);
and on the other activities you extract the URI through:
//Getting the URI from previous activity:
path = getIntent().getExtra("URI");
//Initialising the File form your URI
File StringToBitmap = new File;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
StringToBitmap = new File(path, String.valueOf(options));
//Your bitmap will be stored in mBitmaps
mBitmaps = BitmapFactory.decodeFile(path);
//The next part is extra, if you want to display your bitmap into an ImageView
ImageView iv = new ImageView();
iv = findViewById(R.id.your_id);
iv.setImageBitmap(mBitmaps);
This code worked to me for something very similar. And about that NULL EXCEPTION, every time you get it, try to see if you initialised all your objects correctly. Hope this helps.

Try This:
public Bitmap getScreenShot(View view) {
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return bitmap;
}
public void onShareImage(Bitmap bitmap) {
#SuppressLint("SimpleDateFormat") String fileName = "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".PNG";
storeScreenShot(bitmap, fileName);
Uri imgUri = Uri.fromFile(new File(VarName.SCREENSHOT_DIRECTORY + "/" + fileName));
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, imgUri);
shareIntent.putExtra(Intent.EXTRA_TEXT, VarName.DRESS_ME_SHARE_MASSAGE_HEADER + "\n" + VarName.DRESS_ME_SHARE_APP_LINK);
startActivity(Intent.createChooser(shareIntent, "Share Image"));
}
public void storeScreenShot(Bitmap bm, String fileName) {
File dir = new File(VarName.SCREENSHOT_DIRECTORY);
if (!dir.exists()) {
dir.mkdirs();
File file = new File(dir.getAbsolutePath(), ".nomedia");
try {
file.createNewFile();
final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
final Uri contentUri = Uri.fromFile(file);
scanIntent.setData(contentUri);
sendBroadcast(scanIntent);
} catch (IOException e) {
e.printStackTrace();
}
}
File file = new File(VarName.SCREENSHOT_DIRECTORY, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
file.createNewFile();
final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
final Uri contentUri = Uri.fromFile(file);
scanIntent.setData(contentUri);
sendBroadcast(scanIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
Now you Just need to call function.
Bitmap bitmap = getScreenShot(cardView);
onShareImage(bitmap);

Related

Having trouble sharing an image with an android intent

I am trying to get a image of a view (constraint-layout) and share it via an android send-intent.
I tried a lot of methods, but until now none have worked.
This is what I have so far:
public void shareStatsImage(){
constraintLayout.setDrawingCacheEnabled(true);
Bitmap bitmap = constraintLayout.getDrawingCache();
File path = null;
try {
path = saveImageToExternal(generateImageTitle(), bitmap);
} catch (IOException e) {
e.printStackTrace();
}
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/png");
final File photoFile = new File(Objects.requireNonNull(getActivity()).getFilesDir(), Objects.requireNonNull(path).getAbsolutePath());
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(photoFile));
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share image using"));
}
public static String generateImageTitle(){
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss");
return sdf.format(new Date());
}
public File saveImageToExternal(String imgName, Bitmap bm) throws IOException {
//Create Path to save Image
String appFolder = "test";
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + File.separator + appFolder); //Creates app specific folder
path.mkdirs();
File imageFile = new File(path, imgName+".png"); // Imagename.png
FileOutputStream out = new FileOutputStream(imageFile);
try{
bm.compress(Bitmap.CompressFormat.PNG, 100, out); // Compress Image
out.flush();
out.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(getContext(),new String[] { imageFile.getAbsolutePath() }, null,new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch(Exception e) {
throw new IOException();
}
return imageFile;
}
There are multiple problems with this solution, for example I am getting an error message ("Permission denied for the attachment") when sharing the image to gmail. When uploading the image to google drive I only get an "upload unsuccessful message".
One good thing is that the images seem to appear in the phone's gallery, just not when sharing them via the intent :(
Thanks for your help!
Convert Bitmap to Uri
private Uri getImageUri(Context context, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), inImage, "Image Title", null);
return Uri.parse(path);
}
You can send Image using Uri.
Uri imageUri = set your image Uri;
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.setType("image/jpeg");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "send"));

How to create separate folder for captured images with losing quality

Hi i am trying to create separate folder for captured images with out losing quality using below code but i am getting exception android.os.FileUriExposedException: file:///storage/emulated/0/myFolder/photo_20180504_102426.png exposed beyond app through ClipData.Item.getUri()
what did do mi-stack can some one correct my code
code:
String folder_main = "myFolder";
File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
f.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File file = new File(Environment.getExternalStorageDirectory(), "/myFolder" + "/photo_" + timeStamp + ".png");
imageUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, Constants.CAMERA_REQUEST_CODE);
private void onCaptureImageResult(Intent data) {
try {
Bitmap thumbnail = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
CircleImageView circleImageView = findViewById(formFields.get(imagePosition).getId());
circleImageView.setImageBitmap(thumbnail);
}
Put This on Your oncreate()
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());

Rewrite code android

I need help with my code that save image to device on android but images are not showing in gallery i tried a lot of different code but not working i need implement it to this code
public class SaveImage extends Activity {
public void saveImage(ImageView imageView) {
Drawable image = imageView.getDrawable();
if(image != null && image instanceof BitmapDrawable) {
BitmapDrawable drawable = (BitmapDrawable) image;
Bitmap bitmap = drawable.getBitmap();
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Picster");
dir.mkdirs();
Date now = new Date();
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(now);
String path = dir.getPath() + File.separator;
File file = new File(path + "IMG_" + timestamp + ".jpg");
try {
FileOutputStream stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
galleryAddPic(file.toString());
} catch (Exception e) {
// TODO: handle exception
}
}
}
public void galleryAddPic(String file) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(file);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
}
i call it in other activity like this
final ImageView image = (ImageView) findViewById(R.id.messageImageView);
Uri imageUri = getIntent().getData();
Picasso.with(this).load(imageUri.toString()).into(image);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SaveImage cls2= new SaveImage();
cls2.saveImage(image);
}
});
look on my updated code i add new void galleryAddpic and call it in TRY block it save pictures but still not show in gallery
You just have to add some lines of code to show that image in gallery with instant effect.
Add this code after your file has been created successfully.
Code :
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
Example :
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
Request the media scanner to scan a file and add it to the media database.
VISIT THIS LINK FOR MORE DETAILS :

Can't see pictures saved in a specific folder

My app uses the phone camera to take pictures and save them in a specific folder. I can't see them with Android Gallery or plugging into my pc, but I can using a file manager app.
I found a solution to this: I rename pictures with a file manager app and the I can see them in the gallery.
The code I'm using is:
Intent camera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String dirName = Environment.getExternalStorageDirectory()+"/MyAPP/APP"+ n +".jpg";
Uri uriSavedImage = Uri.fromFile(new File(dirName));
camera.putExtra(MediaStore.EXTRA_OUTPUT,uriSavedImage);
startActivityForResult(camera, 1);
n++;
AndroidManifest:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
for save image to specific folder,
private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/DirName/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/DirName/"), fileName);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
try this for accessing that image
private void showImage(String imageName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/SlamImages");
if (direct.exists()) {
File f = new File(Environment.getExternalStorageDirectory() + "/SlamImages/" + imageName);
if (f.exists() && !imageName.equals("")) {
Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
imgUserLogo.setImageBitmap(bmp);
} else {
imgUserLogo.setImageResource(R.drawable.friend_image);
Toast.makeText(FriendsDetailsActivity.this, "Image Does not exist", Toast.LENGTH_SHORT).show();
}
}
}
I just needed to add some code to scan the picture and add it to the gallery
private void addGallery() {
Intent mediaScanIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
String currentPath = Environment.getExternalStorageDirectory()
+ "/MyAPP/APP" + n + ".jpg";
File f = new File(currentPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
I added it in onActivityResult and it works

How do I save my imageView image into Gallery (Android Development)

I am trying to create an onClick event to save an imageview into the phone Gallery by the click of a Button, below is my code. it does not save into the Gallery, can anyone help me figure out why?
sharebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View b) {
// TODO Auto-generated method stub
//attempt to save the image
b = findViewById(R.id.imageView);
b.setDrawingCacheEnabled(true);
Bitmap bitmap = b.getDrawingCache();
//File file = new File("/DCIM/Camera/image.jpg");
File root = Environment.getExternalStorageDirectory();
File cachePath = new File(root.getAbsolutePath() + "/DCIM/Camera/image.jpg");
try
{
cachePath.createNewFile();
FileOutputStream ostream = new FileOutputStream(cachePath);
bitmap.compress(CompressFormat.JPEG, 100, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
I do this to save Image in gallery.
private void saveImageToGallery(){
imageview.setDrawingCacheEnabled(true);
Bitmap b = imageview.getDrawingCache();
Images.Media.insertImage(getActivity().getContentResolver(), b,title, description);
}
insertImage() will return a String != null if image has been really saved.
Also: Needs permission in the manifest as "android.permission.WRITE_EXTERNAL_STORAGE"
And note that this puts the image at the bottom of the list of images already in the gallery.
Hope this helps.
Suppose the ImageView already keeps the image that you want to save, first, get the Bitmap
imageView.buildDrawingCache();
Bitmap bm=imageView.getDrawingCache();
Then save it with below code:-
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
And do not forget to set this permission in your manifest:-
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You have to save the image to media provider. Here is a simple example:
Uri saveMediaEntry(String imagePath,String title,String description,long dateTaken,int orientation,Location loc) {
ContentValues v = new ContentValues();
v.put(Images.Media.TITLE, title);
v.put(Images.Media.DISPLAY_NAME, displayName);
v.put(Images.Media.DESCRIPTION, description);
v.put(Images.Media.DATE_ADDED, dateTaken);
v.put(Images.Media.DATE_TAKEN, dateTaken);
v.put(Images.Media.DATE_MODIFIED, dateTaken) ;
v.put(Images.Media.MIME_TYPE, “image/jpeg”);
v.put(Images.Media.ORIENTATION, orientation);
File f = new File(imagePath) ;
File parent = f.getParentFile() ;
String path = parent.toString().toLowerCase() ;
String name = parent.getName().toLowerCase() ;
v.put(Images.ImageColumns.BUCKET_ID, path.hashCode());
v.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, name);
v.put(Images.Media.SIZE,f.length()) ;
f = null ;
if( targ_loc != null ) {
v.put(Images.Media.LATITUDE, loc.getLatitude());
v.put(Images.Media.LONGITUDE, loc.getLongitude());
}
v.put(“_data”,imagePath) ;
ContentResolver c = getContentResolver() ;
return c.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, v);
}
public static void addImageToGallery(final String filePath, final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
Check this out: http://developer.android.com/training/camera/photobasics.html#TaskGallery

Categories

Resources