how to send images from one activity to other (using file path) - android

In my app, I am loading images from url's in listview. And onclick of list item I want to show it on next activity. I can pass bitmap through intent,But considering the size restriction of data that can be send through intent I dont want to send this way.
Anybody knows the better way of passing image from one activity to other.
I have heard about storing image in file and sending filepath using intent But don't know how?Please tell me how can I do it?
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
imageview=(ImageView) view.findViewById(R.id.icon);
description=(TextView) view.findViewById(R.id.firstLine);
rating=(TextView) view.findViewById(R.id.text1);
noofDownloads=(TextView) view.findViewById(R.id.text2);
noofComments=(TextView) view.findViewById(R.id.text3);
imageId=(TextView) view.findViewById(R.id.imageIdText);
publishdate=(TextView) view.findViewById(R.id.thirdLine);
attribution=(TextView) view.findViewById(R.id.attributionText);
Intent intent = new Intent(PicturesList.this, PictureDetail.class);
String fileName=description.getText().toString();
fileclass=new FileClass();
fileclass.saveImage(bitmap,fileName);
Intent intent = new Intent(PicturesList.this, PictureDetail.class);
intent.putExtra("imagePath",fileclass.getPath());
intent.putExtra("Description",description.getText());
intent.putExtra("Rate",rating.getText());
intent.putExtra("Downloads",noofDownloads.getText());
intent.putExtra("Comments",noofComments.getText());
intent.putExtra("PublishTime",publishdate.getText());
startActivity(intent);
}
});
}
And I have save images from ListAdapter
in
getview()
{
String fileName=lolpic.getDescription().toString();
FileClass fileclass=new FileClass();
fileclass.saveImage(bitmap,fileName);
and FileClass.java
public class FileClass {
Picture pic;
File file;
public void saveImage(Bitmap myBitmap,String fileName) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Pictures");
String fname = fileName+".png";
file = new File (myDir, fname);
if (file.exists ())
{
file.delete ();
}
try {
FileOutputStream out = new FileOutputStream(file);
//myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
out.write(byteArray);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getPath()
{
return file.getPath();
}
}

use this to store image in sdcard
void saveImage() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
String fname = "MyImage.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
and next get the image path from file.getpath()
and use
intent.putExtra("imagePath", file.getpath());
to send the image through intent and use
String image_path = getIntent().getStringExtra("imagePath");
Bitmap bitmap = BitmapFactory.decodeFile(image_path);
myimageview.setImageDrawable(bitmap);
in your receiving activity to display an image onto the imageview named myimageview
Based on comments, looks like it should be myimageview.setImageBitmap(bitmap) . Didn't test this. But give a try to this also if above doesn't work

sending Activity
final String root = Environment.getExternalStorageDirectory().getAbsolutePath();
pathToImage = root + "/my/image/path/image.png";
Intent intent = new Intent(context, MyActivity.class);
intent.putExtra("imagePath", pathToImage);
startActivity(intent);
And in you receiving activity:
String path = getIntent().getStringExtra("imagePath");
Drawable image = Drawable.createFromPath(path);
myImageView.setImageDrawable(image);

Related

view images in the phone gallery

when I save images, I want image to appear in the gallery, and not only inside the internal storage like apps wallpaper , facebook messenger
my code , On Click Button
holder.img_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
File dir = new File(Environment.getExternalStorageDirectory(), "/Wallpapers");
if(!dir.exists()) {
dir.mkdirs();
}
Bitmap bitmap = ((BitmapDrawable)holder.img_photo.getDrawable()).getBitmap();
saveImage(bitmap,dir);
}
});
funcation saveImage
private void saveImage(Bitmap finalBitmap,File dir) {
Random r = new Random();
String fname = "Image_" + r.nextInt(1000000) + ".jpg";
File file = new File(dir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast toasty = Toasty.success(context,"Saved", Toast.LENGTH_LONG);
toasty.setGravity(Gravity.CENTER, 0, 0);
toasty.show();
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + dir)));
} catch (Exception e) {
e.printStackTrace();
}
}
I dont have any problem saving pictures but I want to show up in the gallery like image applications
Try this to add image in gallery:
public void addImageToGallery(final String filePath, final Context context) {
ContentValues contentValues = new ContentValues();
contentValues.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
contentValues.put(Images.Media.MIME_TYPE, "image/jpeg");
contentValues.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, contentValues);
}
instead of File dir = new File(Environment.getExternalStorageDirectory(), "/Wallpapers");
use
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);

How to download image from imageuri in android from firebase downloadable uri

I have the downloadable uri of my image from firebase storage. On click of button I want to download the image to my phone. I have written the full code, but nothing happens on click of it.
I have the image uri in getIntent().getStringExtra("Image")
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// new DownloadImage().execute(getIntent().getStringExtra("Image"));
Toast.makeText(getApplicationContext(), "Hi", Toast.LENGTH_SHORT).show();
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
Bitmap bitmap = Glide.with(getApplicationContext()).load(getIntent().getStringExtra("Image")).asBitmap().into(100, 100).get();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
Considering your getIntent().getStringExtra("Image") has the image Uri you can use:
Glide
.with(getApplicationContext())
.load(getIntent().getStringExtra("Image"))
.asBitmap()
.into(new SimpleTarget<Bitmap>(100,100) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
//Now save this resource
}
});
NOTE: In this case the exact size must be provided (anything below 1 isn't accepted)

How to save file in Android to specific folder?

btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ivdisplayphoto.setDrawingCacheEnabled(true);
Bitmap bitmap = ivdisplayphoto.getDrawingCache();
String message = getIntent().getExtras().getString("");//== String message= "/folder1/folder2/"
String root = (Environment.getExternalStorageDirectory().getPath()+message);
// String root = (Environment.getExternalStorageDirectory().getPath()+""/folder1/folder2/");
text.setText(root);
final File newDir = new File(root + "//saved_imag");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "photo-"+ n +".jpg";
File file = new File (newDir, fotoname);
if (file.exists ()){
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast.makeText(getApplicationContext(), "safed to your folder", Toast.LENGTH_SHORT ).show();
} catch (Exception e) {
}
}
});
Hey I'm new to Android and I have been trying to make an app.
I am having trouble with part of saving the camera images into the newly created folder.
the problem is in to message variable i can create the file "newDir" if i use simple string "/folder1/folder2/",but if I use the "message" variable
  I cant create it
// Your problem with message variable. Below is working code please go through it.
btnsave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 0);
}
});
//save you image when calling the onActivityResult method after capture image.
//When user click image vai camera then directly store to save_image folder.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image_" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// But the problem it is I want to record the photo in the path rot=root+message
// In another activity I have a qr-code scanner, every qr-code scanned corresponds to a path the content of every qr-code pass of the first activity to the second, the content is stored in the variable "message".
//Then i am obliged to use the variable "message" so that I draw to change the path to store my photo.
String message = getIntent().getExtras().getString("");
String root=Environment.getExternalStorageDirectory().toString();
String rot = root+message;
// String root = (Environment.getExternalStorageDirectory().getPath()+""/folder1/folder2/");
final File newDir = new File(rot + "/dossier_photos");
Here you did simple mistake with Path :
Environment.getExternalStorageDirectory().getPath() = /storage/emulated/0
Environment.getExternalStorageDirectory().getPath()+message = /storage/emulated/0message
So you got error,
here path should be like below:
String root = (Environment.getExternalStorageDirectory().getPath()+"/"+message);

How can I open images that save in internal storage (cache folder in Android/data/%package%/cache) in android gallery

After image was download, I save it in an internal storage at
Android/data/%packagename%/cache directory. below is a code.
private class SaveImageToStorage extends AsyncTask<Void,Void,Void>
{
String picName;
Bitmap bitmap;
public SaveImageToStorage(String name, Bitmap bitmap)
{
this.picName = name;
this.bitmap = bitmap;
}
#Override
protected Void doInBackground(Void... params) {
if(bitmap != null && !picName.isEmpty()) {
File file = new File(feedImagesCacheDir.getPath(), extractImageNameFromUrl(picName));
try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.WEBP, 80, fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
And after all of this I just want to open the image in android gallery.
I try below code and it doesn't work.It show me Toast "can't find the image".
So I've tried remove "file://", then it open gallery with nothing but something like broken image icon.
private void openImageInGallery(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://"+getFeedImagesCacheDir().getPath() + "/" + imgName+".webp"), "image/*");
startActivity(intent);
}
I think that maybe I save it in cache folder, so its became private with only access to my app.
How can I fix this?
Thanks.Sorry for my bad ENG.
Cache Image are not view directly because is save like encrypted format so first you download that image and save into SD card. use below code.
String root = Environment.getExternalStorageDirectory().toString();
String wallpaperFilePath=Android/data/%packagename%/cache/imagename;
File cacheDir = GlobalClass.instance().getCacheFolder(this);
File cacheFile = new File(cacheDir, wallpaperFilePath);
InputStream fileInputStream = new FileInputStream(cacheFile);
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = scale;
bitmapOptions.inJustDecodeBounds = false;
Bitmap wallpaperBitmap = BitmapFactory.decodeStream(fileInputStream, null, bitmapOptions);
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
wallpaperBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
By using this line you can able to see saved images in the gallery view.
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
You can download images into DCIM (your gallery folder in sdCard).
Then use below to open gallery:
public static final int RESULT_GALLERY = 0;
Intent galleryIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent , RESULT_GALLERY );
If you want to get result URI or do anything else use this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case QuestionEntryView.RESULT_GALLERY :
if (null != data) {
imageUri = data.getData();
//Do whatever that you desire here. or leave this blank
}
break;
default:
break;
}
}
Hope this help!

Questions reagarding bitmap image and image storage

I have the bitmap image that I got from my camera activity. Can someone please guide me as to how can I store this image in the gallery?
code:
In my button OnClickListener
Intent campic=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(campic,cameradata );
In my onActivityResult
if(resultCode==RESULT_OK)
{
Bundle bun=data.getExtras();
bmp=(Bitmap)bun.get("data");
SaveIamge(bmp);
iveventpic.setImageBitmap(bmp);
}
call this function to save bitmap in sdcard:
private void SaveIamge(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
By calling this line u have to store that image in the gallery:
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
and Add permission in the manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
MediaStore.Images.Media.insertImage(getContentResolver(), bmp, title, desc);
As seen in this post.

Categories

Resources