Add save as image for share intent - android

I have an activity that parses an image url into an image view using the picasso library and I'm using the ACTION_SEND intent to share the image's url in other apps.
I want to add to the list of app that appears the option of Save as Image where I can save the image view's content as an image in the sd card.
how to do so?
this is my share code
public void share(View v) {
String shareBody = "Check out my: "+infoUrl;
String title;
title = getString(R.string.infographics) + spinnerCountries.getSelectedItem().toString();
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,title);
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share"));
}
Guys, I do know how to save and image and how to store it ... I just want to know how to add the save to gallery option to the ACTION_SEND intent's list

You can get the bitmap from the imageview using
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
And then save the bitmap to disk and then send it using this function
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
Uri bmpUri = Uri.parse(pictureFile);
final Intent emailIntent1 = new Intent( android.content.Intent.ACTION_SEND);
emailIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent1.putExtra(Intent.EXTRA_STREAM, bmpUri);
emailIntent1.setType("image/png");
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}

Related

how to save my QR generated image into gallery android?

Here, I am generating Qr code as an image view. I want to save that image file into phone gallery. Please, help me.
first of all create bitmap from imageview using following code
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
now save this bitmap in internal storage
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new
File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}

The code does not store image from layout in gallery

I am working on app that store its image from resource to gallery. with the below code, it does not give an error but do not work. help me through this.
RelativeLayout fulllayout;
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "/ZXMCO Images");
fulllayout = (RelativeLayout) findViewById(R.id.layout);
public void save()
{
fulllayout.setDrawingCacheEnabled(true);
fulllayout.buildDrawingCache();
Bitmap localBitmap = fulllayout.getDrawingCache();
saveToInternalStorage(localBitmap);
}
private void saveToInternalStorage(Bitmap bitmapImage){
File pictureFile = getOutputMediaFile();
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG,"File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
private File getOutputMediaFile() {
if (! root.exists()){
root.mkdirs();
}
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(root.getPath() + File.separator + mImageName);
return mediaFile;
}
It just show nothing. run without an error but could not find the image in gallery.
I Think the problem here is the Gallery didn't know that theres new images is stored on the device so we will need to notify it
There's two way to do that
Pre - Kitkat
using Boradcast
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
Kitkat
You Can user the MediaScannerConnection to scan the new files
MediaScannerConnection.scanFile(context, new String[]{imageURL}, null,implment Listener Here);

Retrieving the image from a folder : Android

public void onPictureTaken(byte[] data, Camera camera)
{
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Folder/Raw Image");
imagesFolder.mkdirs();
Date d = new Date();
CharSequence s = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());
File output = new File(imagesFolder, s.toString() + ".jpg");
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{}
Log.d("Log", "onPictureTaken - jpeg");
File filenew = new File(android.os.Environment.getExternalStorageDirectory(),"Folder/Raw Image");
bitmap=BitmapFactory.decodeFile(filenew.getAbsolutePath());
Each time when i capture image, the image save to sub folder "Raw Image" which is in a folder " Folder". I need to retrieve this image for further processing. so i used Bitmapfactory.options. All this has to be done under one button click. every image that is saved has to be processed. How can i retrieve in such a way.
If you are taking photos, what you can do is startActivityForResult, during this process you have to work with the URI. The URI is the path that you have specified for your picture.
And now during your onActivityResult(..) call you can do the following:
try {
Bitmap thumb = MediaStore.Images.Media.getBitmap(
activity.getContentResolver(), fileUri);
photo.setImageBitmap(thumb);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Where fileUri is the URI of the image I was talking about. Here photo is the ImageView. Also when working with different devices there is a possibility that you may get an error, so I best advice you to save the URI path in a SharedPreference.
You are pointing to the wrong path :
Environment.getExternalStorageDirectory().toString() + "/"+ Folder + "Raw Image"+ ".jpg";
But you have created folder like this,
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Folder/Raw Image");
Try this way, It may help you.
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Folder/RawImage");
imagesFolder.mkdirs();
File output = new File(imagesFolder,"temp" + ".jpg");
Above we have declared a static file name. The file will be replace for every image capture.
Now you know the filepath,
String mFilePath = Environment.getExternalStorageDirectory() + "Folder/RawImage/temp.jpg";
You can use this filepath in the following way to show the bitmap.
myImage.setImageUri(Uri.fromFile(new File("Your file path")));
Or with:
myImage.setImageUri(Uri.parse(new File("Your file path").toString()));
You can get the bitmap :
Bitmap bmp=BitmapFactory.decodeStream(getContentResolver().openInputStream(Your image URI));

How to pass the captured image to a different activity to set to the image view in android and store in a databse

Can anybody tell how to pass the captured image to a different activity to set the image view in android and store in a database? Can anybody provide code?
Thanks
Try this...
1.Capture and get the bitmap of the captured image in the onActivityResult()
public void capture(View view) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAPTURE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CAPTURE_REQUEST) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
}
}
}
2 Send the Image to the next Activity...You can send the Bitmap because it implements Parcelable
private void sendImage() {
Intent intent = new Intent(MainActivity.this, NextActivity.class);
intent.putExtra("image", thumbnail);
startActivity(intent);
}
3 Get the image in the NextActivity
Bundle extras = getIntent().getExtras();
if (extras != null) {
Bitmap image = (Bitmap) extras.get("image");
if (image != null) {
imageView.setImageBitmap(image);
}
}
you need to follow these steps :-
capture image using camera
save this image
get the file URI
In your next activity you can show this image using that file URI
let me know if you have any issue.
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}

android save images to internal storage

I'm having problems implementing this code Saving and Reading Bitmaps/Images from Internal memory in Android
to save and retrieve the image that I want, here is my code:
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory, + name + "profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
and to retrieve(I don't know if I'm doing wrong)
#Override
protected void onResume()
{
super.onResume();
try {
File f = new File("imageDir/" + rowID, "profile.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
image = (ImageView) findViewById(R.id.imageView2);
image.setImageBitmap(b);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and nothing happens so what should I change??
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
I think Faibo's answer should be accepted, as the code example is correct, well written and should solve your specific problem, without a hitch.
In case his solution doesn't meet your needs, I want to suggest an alternative approach.
It's very simple to store image data as a blob in a SQLite DB and retrieve as a byte array. Encoding and decoding takes just a few lines of code (for each), works like a charm and is surprisingly efficient.
I'll provide a code example upon request.
Good luck!
Note that you are saving the pick as name + profile.jpg under imageDir directory and you're trying to retrieve as profile.jpg under imageDir/[rowID] directory check that.
I got it working!
First make sure that your app has the storage permission enabled:
Go to Device Settings>Device>Applications>Application Manager>"your app">Permissions>Enable Storage permission!
Permissions in manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
So, if you want to create your own directory in your File Storage you can use somethibng like:
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
refreshGallery(outFile);
Else, if you want to create a sub directory in your default device DCIM folder and then want to view your image in a separate folder in gallery:
FileOutputStream fos= null;
File file = getDisc();
if(!file.exists() && !file.mkdirs()) {
//Toast.makeText(this, "Can't create directory to store image", Toast.LENGTH_LONG).show();
//return;
print("file not created");
return;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmsshhmmss");
String date = simpleDateFormat.format(new Date());
String name = "FileName"+date+".jpg";
String file_name = file.getAbsolutePath()+"/"+name;
File new_file = new File(file_name);
print("new_file created");
try {
fos= new FileOutputStream(new_file);
Bitmap bitmap = viewToBitmap(iv, iv.getWidth(), iv.getHeight() );
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Toast.makeText(this, "Save success", Toast.LENGTH_LONG).show();
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
print("FNF");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
refreshGallery(new_file);
Helper functions:
public void refreshGallery(File file){
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
}
private File getDisc(){
String t= getCurrentDateAndTime();
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
return new File(file, "ImageDemo");
}
private String getCurrentDateAndTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String formattedDate = df.format(c.getTime());
return formattedDate;
public static Bitmap viewToBitmap(View view, int width, int height) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
Hope this helps!

Categories

Resources