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)
Related
I am having an application containing different images using ImageView and ViewPager. I want to save the current image shown through ImageView in SD Storage. But it always saved in Phone Storage successfully.
I want to save the image in SD Card and also saved image not showing in Gallery Why? Kindly help me out in this issue:
public void SaveIamge() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Cute_Baby_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);
int currentImagePos = viewPager.getCurrentItem();
Drawable drawable = viewPager.getResources().getDrawable(images[currentImagePos]);
Bitmap finalBitmap = ((BitmapDrawable) drawable).getBitmap();
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();
}
Toast.makeText(this, "Sucessfully Save Image", Toast.LENGTH_LONG).show();
}
Environment.getExternalDirectory() returns phone storage. To get location of SD card, check Find an external SD card location
To make the images appear in gallery, you should let the media scanner scan the file using MediaScannerConnection.scanFile()
Check Image, saved to sdcard, doesn't appear in Android's Gallery app
Create a function called getDirectory()
private static File getDirectory(String variableName, String... paths) {
String path = System.getenv(variableName);
if (!TextUtils.isEmpty(path)) {
if (path.contains(":")) {
for (String _path : path.split(":")) {
File file = new File(_path);
if (file.exists()) {
return file;
}
}
} else {
File file = new File(path);
if (file.exists()) {
return file;
}
}
}
if (paths != null && paths.length > 0) {
for (String _path : paths) {
File file = new File(_path);
if (file.exists()) {
return file;
}
}
}
//If any there is no SECONDARY STORAGE are detected return INTERENAL STORAGE
return Environment.getExternalStorageDirectory();
}
Change your code to
public void SaveIamge() {
String root = getDirectory("SECONDARY_STORAGE").getAbsolutePath();
File myDir = new File(root + "/Cute_Baby_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);
int currentImagePos = viewPager.getCurrentItem();
Drawable drawable = viewPager.getResources().getDrawable(images[currentImagePos]);
Bitmap finalBitmap = ((BitmapDrawable) drawable).getBitmap();
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();
}
Toast.makeText(this, "Sucessfully Save Image", Toast.LENGTH_LONG).show();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + root)));
}
I have added a broadcast to notify the MediaScanner to re-scan the filesystem for new files. This will fix the problem of images are not showing in the gallery.
I create take a screenshot in Android through a button click, but image can't be saved. I have an error message in "No such file or directory". What can I do?
My code:
public class MainActivity extends Activity {
LinearLayout L1;
ImageView image;
Bitmap bm;
File file;
FileOutputStream fileoutputstream;
View v1;
ByteArrayOutputStream bytearrayoutputstream;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bytearrayoutputstream = new ByteArrayOutputStream();
L1 = (LinearLayout) findViewById(R.id.layout);
Button but = (Button) findViewById(R.id.Button01);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.ImageView02);
image.setBackgroundDrawable(bitmapDrawable);
Log.e("top-->", String.valueOf(bitmapDrawable));
bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);
//String path = Environment.getExternalStorageDirectory().toString();
File myDir = new File(Environment.getExternalStorageDirectory(), "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);
bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
final ScrollView scrollview = (ScrollView) findViewById(R.id.scroll);
scrollview.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener(){
#Override
public void onScrollChanged() {
if (scrollview != null) {
if (scrollview.getChildAt(0).getBottom() <= (scrollview.getHeight() + scrollview.getScrollY())) {
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.ImageView02);
image.setBackgroundDrawable(bitmapDrawable);
Log.e("top-->", String.valueOf(bitmapDrawable));
bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);
//String path = Environment.getExternalStorageDirectory().toString();
File myDir = new File(Environment.getExternalStorageDirectory(), "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);
bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
} else {
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.ImageView01);
image.setBackgroundDrawable(bitmapDrawable);
Log.e("bottom-->", String.valueOf(bitmapDrawable));
bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);
// String path = Environment.getExternalStorageDirectory().toString();
File myDir = new File(Environment.getExternalStorageDirectory(), "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);
bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
});
}
}
Image can't be saved in sdcard. What mistake did I make? I can't understand what is the problem or how to save an image on sdcard?
I use this method to capture screen. First, add proper permission to save file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the code (running in an Activity):
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}
And this is how you can open the recently generated image:
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}
Try this,
Before write the file you have to check the permissions for marshmallow
public static final int REQUEST_STORAGE = 101;
if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (!hasPermissions(mContext, PERMISSIONS)) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST_STORAGE);
} else {
writeFile()
}
}
/*check permissions for marshmallow*/
#SuppressWarnings("BooleanMethodIsAlwaysInverted")
private static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
/*get Permissions Result*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("TAG", "PERMISSION_GRANTED");
writeFile();
} else {
Toast.makeText(mContext, "The app was not allowed to write to your storage", Toast.LENGTH_LONG).show();
}
}
}
}
public void writeFile()
{
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.ImageView02);
image.setBackgroundDrawable(bitmapDrawable);
Log.e("top-->", String.valueOf(bitmapDrawable));
bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);
//String path = Environment.getExternalStorageDirectory().toString();
File myDir = new File(Environment.getExternalStorageDirectory(), "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);
bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
final String root = Environment.getExternalStorageState().toString();
File myDir=new File(root + "/saved_images/" );
State is no storage. Change to:
File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images" );
And adapt your code for mkdirs as explained in comment.
if (!myDir.exists())
{
if (!myDir.mkdirs())
{
Toast.makeText(this, "Sorry could not create directory:\n" + myDir.getAbsolutePath(), Toast.LENGTH_LONG).show();
return;
}
}
You complain that the file is not created but it starts with the directory.
You never answered my question about Androud version. But for 6.0 and above you should ask the user also for runtime permission. Add that code.
Or, as a quick solution, go to the Android settings of your app and switch the Storage toggle button to ON.
I had uploaded the image on Firebase Storage successfully. I have the URI and using Glide, I'm able to show the image on an ImageView. I want to save this image on my SD card but I'm getting an exception
java.io.FileNotFoundException: No content provider:
https://firebasestorage.googleapis.com/..
In here:
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), myUri);
SaveImage(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
Here is my complete code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_pic);
Intent intent = getIntent();
String str = intent.getStringExtra("pic");
Uri myUri = Uri.parse(str);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), myUri);
SaveImage(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
ImageView imageView = (ImageView)findViewById(R.id.displayPic);
Glide.with(getApplicationContext()).load(myUri)
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageView);
}
private void SaveImage(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();
}
}
URI looks like this:
https://firebasestorage.googleapis.com/example.appspot.com/o/pics%2Fc8742c7e-8f59-4ba3-bf6f-12aadfdf4a.jpg?alt=media&token=9bsdf67d-f623-4bcf-95d7-5ed97ecf1a21
Using Glide Try this.
Bitmap bitmap= Glide.
with(this).
load(mDownloadUrl).
asBitmap().
into(100, 100). // Width and height
get();
SaveImage(bitmap);
where mDownloadUrl is your image URL.
Firebase Storage does not have a registered content resolver. The download Url you get is actually a plain vanilla https:// Url that you can feed into Glide.
You can also download this Url directly. Check out this question.
Just call downloadUri.toString() to get the download Url in string form.
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);
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);