I have stored some images in res folder of my app. But the user can download this image to their sdcard using the download option. How can I copy the image in res folder to sdcard. Can anyone help me.
You can do something like this,
if (isSdPresent()) { // to check is sdcard mounted
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bbicon = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
String extStorageDirectory = Environment.getExternalStorageDirectory()+ File.separator + "FolderName";
File wallpaperDirectory = new File(extStorageDirectory);
wallpaperDirectory.mkdirs();
OutputStream outStream = null;
File file = new File(wallpaperDirectory,"icon.png");
//to get resource name getResources().getResourceEntryName(R.drawable.icon);
try {
outStream = new FileOutputStream(file);
bbicon.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
}
to check SDCard
public boolean isSdPresent() {
return android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
}
Maybe this could help you getting a stream from your image and posting it to the user to download...
Related
I am trying to store my image from imageView in bitmap, so that I can store it in the gallery of the android device. Every time I save an image, the background of the imageView is not stored. What am I missing?
Here is my code:
ImageView imageView = (ImageView) findViewById(R.id.img);
imageView.setBackgroundResource(R.drawable.img1);
BitmapDrawable draw = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = draw.getBitmap();
Code to store the image into the gallery is:
FileOutputStream outStream = null;
File dir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyAlbum");
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.d("MyAlbum", "failed to create directory");
Toast.makeText(MainActivity.this, "Failed to make directory", Toast.LENGTH_SHORT).show();
}
}
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
try {
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(getApplicationContext(), "PICTURE SAVED", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(dir));
sendBroadcast(intent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can take a screenshot of this view (ImageView) in this case, it will simply take what's drawn on this view at this moment and turn it into a bitmap you can save.
Answer is mentioned here already.
The magical part is that
ImageView yourImageView = .. // Get reference it to your view.
yourImageView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(yourImageView.getDrawingCache());
yourImageView.setDrawingCacheEnabled(false);
Ta-da you can use your snapshot btimap.
you can try this out,
private void saveImageToStorage(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();
Log.i("LOAD", root + fname);
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Happy coding :-)
How to write image in phone directory. Directory is created but i could not write image in this folder. Here is my code .please check if i am doing something wrong thanks in advance.
Bitmap bitmap;
String directory = new_path; // I am getting path here of image like sdcard/0/emulated/image.jpg
String folder_name = "abc"
bitmap = BitmapFactory.decodeFile(directory);
iv_6.setImageBitmap(bitmap); // image displayed here but not saving in directory.
try {
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator +folder_name);
f.mkdirs();
FileOutputStream fo = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, fo);
fo.close();
}catch (Exception e)
{
e.printStackTrace();
}
public void savePng(Bitmap bitmap, String filePath) {
try {
File temp = new File(filePath);
FileOutputStream os = new FileOutputStream(temp + ".png");
bitmap.compress(Bitmap.CompressFormat.PNG, 50, os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I currently save images that I download from the internet to disk. I want to be able to delete the images when the user closes the app. I want the images all saved in one folder so it will be easy to delete them. I did getActivity().getCacheDir().getAbsolutePath()+ File.separator + "newfoldername" to get a path to a folder. Not sure how to add the images into the folder.
public void saveImage(Context context, Bitmap b, String name_file, String path) {
FileOutputStream out;
try {
out = context.openFileOutput(name_file, Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.JPEG,90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public Bitmap getImageBitmap(Context context, String name) {
try {
FileInputStream fis = context.openFileInput(name);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap b = BitmapFactory.decodeStream(fis,null, options);
b.getAllocationByteCount());
fis.close();
return b;
} catch (Exception e) {}
return null;
}
You shouldn't save the images on your cache folder as you can't rely on it as per the documentation. A better approach would be to store them on your SD Card. As per the documentation :
public abstract File getCacheDir()
Returns the absolute path to the application specific cache directory on the filesystem. These files will be ones that get deleted first when the device runs low on storage. There is no guarantee when these files will be deleted. Note: you should not rely on the system deleting these files for you; you should always have a reasonable maximum, such as 1 MB, for the amount of space you consume with cache files, and prune those files when exceeding that space.
FOR SAVING
private String saveToInternalSorage(Bitmap bitmapImage){
File directory = getApplicationContext().getDir("MY_IMAGE_FOLDER"
,Context.MODE_PRIVATE);
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return directory.getAbsolutePath();
}
FOR READING
private void loadImageFromStorage(String path)
{
try {
File file = new File(path, "Image.jpg");
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
ImageView img = (ImageView)findViewById(R.id.my_imgView);
img.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FOR DELETING :
String dir = getApplicationContext().getDir("MY_IMAGE_FOLDER"
,Context.MODE_PRIVATE);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
new File(dir, children[i]).delete();
}
}
I use following code to write an image to external storage in android :
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
fileName = "image_2.jpeg";
File file = new File(dir, fileName);
try {
FileOutputStream outStream = new FileOutputStream(file);
Bitmap bitmap = BitmapFactory.decodeFile("android.resource://com.mypackage.com/drawable/image_1");
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This code is for reading image_1.jpg from drawable folder, then writing it to download folder in external storage, with image_2.jpeg name. (create download folder in external storage and a file with image_2.jpeg name inside that folder).
This code will produce an ((force close)). download folder is created and also the image_2.jpeg is created, but image image_2.jpeg is corrupted.
These images in drawable folder can be accessed by BitmapFactory, you can save the bitmap to PNG or JPG.
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
File sd = Environment.getExternalStorageDirectory();
String fileName = "test.png";
File dest = new File(sd, fileName);
try {
FileOutputStream out;
out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Don't forget to add android.permission.WRITE_EXTERNAL_STORAGE permission.
For other type of images, I think put them into assets folder is a better way.
There is a sample here.
I did same thing with this code.Try this code:
String[] sampleImagesName = { "image2" };
int[] sampleImages = { R.drawable.image1};
File file;
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/download");
if (!file.exists()) {
file.mkdirs();
SaveSampleToSD();
}
}
private void SaveSampleToSD() {
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/download";
for (int i = 0; i < sampleImages.length; i++) {
try {
File f = new File(path + "/", sampleImagesName[i] + ".jpg");
Bitmap bm = BitmapFactory.decodeResource(getResources(),
sampleImages[i]);
FileOutputStream out = new FileOutputStream(f);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
Log.e("ImageSaved---------", "saved");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
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!