I have more then 50 images in my res/drawable folder. I want to save these images to external storage and then display these image one by one in an image view/image switcher. I used below code to save single image to external storage. but i am unable to figure it out how can i save all these images to external storage altogether (at once).
public void SaveImage(){
if (!CheckExternalStorage()) {
return;
}
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.a01);
try {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
OutputStream fOut = null;
File file = new File(path, "image1.png");
file.createNewFile();
fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
Log.i(LOGTAG, "Image Written to Exterbal Storage");
} catch (Exception e) {
Log.e("saveToExternalStorage()", e.getMessage());
}
}
Using an answer from : https://stackoverflow.com/a/3221787/794088 with some modification to call your method SaveImage with a param
...
R.drawable drawableResources = new R.drawable();
Class<R.drawable> c = R.drawable.class;
Field[] fields = c.getDeclaredFields();
for (int i = 0, max = fields.length; i < max; i++) {
final int resourceId;
try {
resourceId = fields[i].getInt(drawableResources);
// call save with param of resourceId
SaveImage(resourceId);
} catch (Exception e) {
continue;
}
}
...
public void SaveImage(int resId){
if (!CheckExternalStorage()) {
return;
}
Bitmap bmp = BitmapFactory.decodeResource(getResources(), resID);
try {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
OutputStream fOut = null;
File file = new File(path, "image1.png");
file.createNewFile();
fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
Log.i(LOGTAG, "Image Written to Exterbal Storage");
} catch (Exception e) {
Log.e("saveToExternalStorage()", e.getMessage());
}
}
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 have the following code:
YuvImage yuv = new YuvImage(result.getExtractImageData(),
camera.getParameters().getPreviewFormat(),
result.getWidth(),
result.getHeight(), null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
yuv.compressToJpeg(new Rect(0, 0, result.getWidth(), result.getHeight()), 100, out);
byte[] bytes = out.toByteArray();
Bitmap image = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
image = RotateImage(image, rotation);
createDirectoryAndSaveFile(image, "Image_" + result.getCaptureTime() + ".jpg");
String filePath = Environment.getExternalStorageDirectory() + "/MyFolder/Image_" + result.getCaptureTime() + ".jpg";
try {
ExifInterface exif = new ExifInterface(filePath);
exif.getAttribute("UserComment");
// call this next setAttributes a few times to write all the GPS data to it.
exif.setAttribute("UserComment", String.valueOf(result.getCaptureTime()));
exif.saveAttributes();
}
catch (IOException e) {
e.printStackTrace();
}
It is supposed to punt under UserComment the result.getCaptureTime() at which it was captured from the camera. I download it to a Windows folder and I can't see the properties I just created...
What I'm doing wrong?
EDIT:
private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName)
{
File direct = new File(Environment.getExternalStorageDirectory() + "/MyFolder");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/MyFolder/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/MyFolder/"), fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I want to save a created bitmap after a button clicked
How can I do that? and if possible to a specific location
Here are my codes:
quoteimage.requestLayout();
if (quoteimage.getViewTreeObserver().isAlive()) {
quoteimage.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
// we check which build version we are using
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
quoteimage.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
quoteimage.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
viewToBitmap(quoteimage); ///this one creates the bitmap
}
});
}
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
///Here I want to save the bitmap
}
});
Call save() in onClick():
protected void save(){
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}}
Use this method to save your bitmap, also pass the file name and location as U like
private createDirectoryAndSaveFile(Bitmap imageToSave, String fileName,String location) {
File direct = new File(Environment.getExternalStorageDirectory() + "/"+location);
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/"+location+"/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/"+location+"/"), fileName+".jpg");
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
File externalFile = new File(Environment.getExternalStorageDirectory(),"your/location/"+fileName+".jpg");
externaluri = Uri.parse(externalFile.getPath());
Log.d("externaluri", externaluri.toString());
}
Example
createDirectoryAndSaveFile(yourbitmap, "your_image_name" ,"your/location");
Android Saving created bitmap to directory on sd card
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg")
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
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();
}
}
}