I have an image to the right and a button "download" to the left. the image is from my drawable. now,when i try to click the download i want to put the image to my sdcard downloads. Please help me i only see about download in url. is there other solution for this . Thanks
public class ImageDownloader {
public void download(String url, ImageView imageView) {
BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
task.execute(url);
}
}
/* class BitmapDownloaderTask, see below */
}
First, you need to get your Bitmap. You can already have it as an object Bitmap, or you can try to get it from the ImageView such as:
BitmapDrawable drawable = (BitmapDrawable) ImageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Then you must get to directory (a File object) from SD Card such as:
File sdCardDirectory = Environment.getExternalStorageDirectory();
Next, create your specific file for image storage:
File image = new File(sdCardDirectory, "test.png");
After that, you just have to write the Bitmap such as:
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Finally, just deal with the boolean result if needed. Such as:
if (success) {
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
Don't forget to add the following permission in your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Related
I have two Image-View in a layout, one as at background and another is above that(at foreground) and I want to save both the images. So can anyone help me out that how can I save both the images into the device storage as single image.
Thank you.
A simple solution I found here is to put both of your imageView in a single Layout and then save your layout as a Bitmap. I will retype the solution code here
private Bitmap getBitmap(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
// Reset the drawing cache background color to fully transparent
// for the duration of this operation
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
Toast.makeText(StopWarApp.getContext(), "Something went wrong",
Toast.LENGTH_SHORT).show();
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
// Restore the view
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
Now that you have your Bitmap, you can save it to your storage like this
private void saveImage(Bitmap finalBitmap, String image_name) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root);
myDir.mkdirs();
String fname = "Image-" + image_name+ ".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();
}
}
Don't forget to add your permissions in the manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I know this question has been answered, but I would like to get a better explanation as I have tried implementing it but it doesn't seem to work.
I have the following code :
private void takeScreenshot() {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
//Get screenshot
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
Date fileName = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", fileName);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File image = new File(directory,fileName+".jpg");
try {
FileOutputStream fos = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
}
}
What I would like to happen is to take a screenshot of the screen, save it to a folder with my app name, and have it be readable by the android phone's gallery. My code does none of the above. I do not see any folder w/ the name of my app when I use file explorer, and it doesn't appear in the gallery as well. It seems it doesn't even save the image. Can you please tell me what is wrong with my code?
The code below creates a directory called "AppName" and then stores the screenshot in that directory. This will be readable by the gallery as well. Your code (and the code below) will not work if you do not have the WRITE_EXTERNAL_STORAGE permission.
private static File getOutputMediaFile() {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp"); //change to your app name
// 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()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");
return mediaFile;
}
private void takeScreenshot(){
//Get screenshot
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File pictureFile = getOutputMediaFile();
if (pictureFile == null){
Log.d(TAG, "error creating media file, check storage permission");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
bitmap.recycle();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found" + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
Ensure to add
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
to your manifest and ask for permissions on runtime with
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
00);
The code finds and/or creates a directory with the app name in the getOutputMediaFile() method, then returns a file in the directory with timestamp as its name. Then in the takeScreenshot() method, the screenshot bitmap is converted to a byte[] and a fileOutputStream is used to write this byte[] to the file returned by getOutputMediaFile().
The result is a screenshot saved to the gallery in the directory "MyCameraApp" (Change to whatever your app's name is)
Hope this helps!
I have an imageview which is loaded using a url.
I want to download the image in the view and store it in internal/external drive of mobile. But i tried all possible method on Stackoverflow couldn't access the drive even with the premission given on the mobile to access read and write in the external memory. Nothing seems to work i don't know why?
This is my Code, can you please tell me where I am going wrong?
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
File sdCardDirectory = Environment.getDataDirectory();
File image = new File(sdCardDirectory, "test.png");
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
Manifest permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
File sdCardDirectory = Environment.getDataDirectory();
That is not the sd card directory.
Environment.getDataDirectory().getAbsolutePath() == /data
You have no write permission there. Better use
File sdCardDirectory = Environment.getExternalStorageDirectory();
That will work if you got your permissions right.
But it will not save to the SD card!
I'm trying to include image sharing in my application and everything is working but the share chooser takes long time to appear on devices
here is what i'm doing:
I have ImageView "items_details_image" and I want to share its image to be able to send it through whatsapp and other apps
void ShareImg() {
try {
Uri bmpUri = getLocalBitmapUri(items_details_image);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
// Launch sharing dialog for image
startActivity(Intent.createChooser(shareIntent, "Share Image"));
} else {
// ...sharing failed, handle error
}
} catch (Exception e) {
}
}
here is how I get bitmap from Image URL
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
I don't know why it is taking longer than usual comparing it with other apps on the same device such as gallery or whatever
You are doing disk I/O on the main application thread, in getLocalBitmapUri(). This will freeze your UI as long as it takes to write your bitmap to disk.
I'm having some trouble. I'm new to java and Android programming. I'm using a template to get started and I'm stuck.
I have a app that pulls images from my Tumblr Feed and presents them on the screen with a download button. It works fine but installs to the root of the internal storage. How do I save it to a folder in the internal storage called "/Pictures/Tumblr"?
My code is:
public void onLoadingComplete(final String imageUri, View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
// close button click event
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, "tumblr_"+images.get(position).getId()+".jpg");
try {
fOut = new FileOutputStream(file);
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
String saved = getResources().getString(R.string.saved);
Toast.makeText(getBaseContext(), saved + " " + file.toString(), Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
I've tried changing the
File file = new File(path, "tumblr_"+images.get(position).getId()+".jpg");
To
File file = new File(path+"/Pictures/Tumblr", "tumblr_"+images.get(position).getId()+".jpg");
But I know it's wrong.
Can anyone help?