Store Bitmap image to SD Card in Android - android

I am facing some strange problem with my android code,
I have an image in Bitmap variable and want to save that file to SD card.
I code as follow,
Bitmap IMAGE // Loaded from internet servers.;
try {
File _sdCard = Environment.getExternalStorageDirectory();
File _picDir = new File(_sdCard, "MyDirectory");
_picDir.mkdirs();
File _picFile = new File(_picDir, "MyImage.jpg");
FileOutputStream _fos = new FileOutputStream(_picFile);
IMAGE.compress(Bitmap.CompressFormat.JPEG, 100, _fos);
_fos.flush();
_fos.close();
Toast.makeText(this, "Image Downloaded", 7000).show();
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(this, ex.getMessage(), 7000).show();
}
I am using Sony Experia Arc as my testing device, when the phone is connected to my computer, the code works nice, it stores image and also displays in gallery. But when I disconnect phone from my computer and test the app, it doesn't save picture and doesn't show any exception.

use this function
void saveImage() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
String fname = "Image.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();
}
}
Check this answer will give more details Android saving file to external storage

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

**This Code Cover the Following Topics**
1. Save a bitmap Image on sdcard a jpeg
2. Create a folder on sdcard
3. Create every file Separate name
4. Every file save with date and time
5. Resize the image in very small size
6. Best thing image Quality fine not effected from Resizing
The following method is used to create an image file using the bitmap
public void createImageFromBitmap(Bitmap bmp) {
FileOutputStream fileOutputStream = null;
try {
// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Capture/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
//Capture is folder name and file name with date and time
fileOutputStream = new FileOutputStream(String.format(
"/sdcard/Capture/%d.jpg",
System.currentTimeMillis()));
// Here we Resize the Image ...
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100,
byteArrayOutputStream); // bm is the bitmap object
byte[] bsResized = byteArrayOutputStream.toByteArray();
fileOutputStream.write(bsResized);
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Related

Problems saving and retrieving images

Ok i'm completely editing this post... I have made it so that I can save the file path to my data base. this works and is saved as /storage/emulated/0/1508blah blah.jpg . Now i cannot get my code to read this item back into a picture.
imagePhoto = (ImageView)findViewById(R.id.detail_recipe_image);
Toast.makeText(this, recipe.image, Toast.LENGTH_SHORT).show();
Bitmap bmp = BitmapFactory.decodeFile(String.valueOf(recipe.image));
imagePhoto.setImageBitmap(bmp);
am I missing something here? cause the Toast Is reading the recipe.image just fine and is displaying the path. why Is the rest not displaying the image?
Storage Code
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
String picturePath = destination.toString();
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
textImagePath.setText(picturePath.toString());
ImageView img = (ImageView)findViewById(R.id.addphotoview);
img.setImageBitmap(thumbnail);
}
Adding in the files paths seem to be the best solution to the problem i am having so that you #ModularSynth for your help with this. Always making sure all the info is your code to make the file paths work helps.

android - add images from drawable folder into a created file directory

I'm looking to be able to take png images (called 1.png, 2.png, 3.png) that I have stored in my apps drawable folder and copy/save them to a file directory that is created by my app on launch.I've tried .createnewfile() but was unable to get anything to work.code for creating my file directory below:
//-----create file directory for images
public void createDirectory() {
try {
File imageDirectory = new File(Environment.getExternalStorageDirectory() + "/DCIM/C2AT_IMAGES");
if (!imageDirectory.exists()) {
imageDirectory.mkdirs();
//something here to take images from drawable folder and place them into my newely created directory
File imageFile = new File(Environment.getExternalStorageDirectory() + "/DCIM/C2AT_IMAGES", //something here getDrawable maybe?
);
imageFile.createNewFile();
}
}
catch (Exception e) {
Log.d("MAKE_DIR", "error creating directory");
}
}
thanks
Solved, this is how I done it:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.maptile_1);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory() + "/DCIM/C2AT_IMAGES"
+ File.separator + "test.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
e.printStackTrace();
toastMsg = e.toString();
toast();
}

How to create a folder and save more than one files to that folder in android?

Im using the code as shown bellow for saving a jpg file to sdcard on a button click.
OutputStream fOut = null;
try
{
fOut = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
mMergedLayersBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
for saving the image to a folder, I rewrite the code as shown bellow
OutputStream fOut = null;
//Create Folder
File folder = new File(Environment.getExternalStorageDirectory().toString()+"/draw/Images");
folder.mkdirs();
//Save the path as a string value
String extStorageDirectory = folder.toString();
//Create New file and name it draw.jpg
File file = new File(extStorageDirectory, "draw.jpg");
try
{
fOut = new FileOutputStream(file);
mMergedLayersBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
Now its rewriting the image when I am click the save button second time. I want to save the whole image that im saving to a folder. I don't know how to change my code for this requirement. If anyone know about this, please help me..
Since you have hardcoded the name of the image as "draw.jpg", each time your image gets overwritten. So instead of hardcoding provide a dynamic name.
For Example, instead of,
File file = new File(extStorageDirectory, "draw.jpg");
try
File file = new File(extStorageDirectory, System.currentTimeMillis()+"draw.jpg");

StreamCorruptedException when reading Bitmap from SD card

I have a web service that returns a jpg. I read this jpg into a byte[], convert to a Bitmap, and save it to the SD card. The next time the user comes to this Activity, it will search the SD card to see if the image exists before hitting the web service.
However, the code that checks the SD card returns a StreamCorruptedException if the file exists.
Here is my code that writes to the SD card:
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String root = Environment.getExternalStorageDirectory().toString();
new File(root + "/images").mkdirs();
try {
File file = new File(root + "/images", Integer.toString(intImageId) + "m.jpg");
FileOutputStream os = new FileOutputStream(file);
Bitmap theImageFromByteArray = BitmapFactory.decodeByteArray(image, 0, image.length);
theImageFromByteArray.compress(Bitmap.CompressFormat.JPEG, 80, os);
os.flush();
os.close();
}
catch (FileNotFoundException e) {
}
catch (IOException e) {
}
}
Here is my code that checks the SD card for the existing image:
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
|| Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
try {
File file = new File(Environment.getExternalStorageDirectory() + "/images", Integer.toString(mImageId) + "m.jpg");
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
mImage = (Bitmap)ois.readObject();
ois.close();
}
catch (Exception e) {
}
}
The exception happens during new ObjectInputStream(fis)
You cannot arbitrarily readObject() like this. writeObject() needs to be used in order for readObject() to detect a valid serialized object.

Store and retrieve images into sdcard

I have a set of image urls. I download it to bitmap. Now I want to store these images into sdcard/project folder. If I don't have such a file, I have to create it. What I have done right now is:
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, imageName);
if(!file.exists()) {
file.mkdir();
try {
fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(), "file://"
+ file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
But I am not getting images inserted into sdcard. What is wrong in my code? Please reply. Thanks in advance.
Try using the below code:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
String fileName = edtNameImage.getText().toString().trim();//this can be changed
if (fileName.equalsIgnoreCase("")) {
Toast.makeText(context, "Fields cannot be left blank",
Toast.LENGTH_SHORT).show();
return false;
}
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + fileName);
// write the bytes in file
FileOutputStream fo;
try {
file.createNewFile();
fo = new FileOutputStream(file);//snapshot image is the image to be stored.
if (snapShotImage!=null)
{
snapShotImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
}else{
return false;
}
fo.write(bytes.toByteArray());
// ChartConstants.IMAGE_STORAGE++;
fo.flush();
fo.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return true;
You can also check for duplicacy in names with some additional code lines.
Let me know if it helps.
Have you made sure that the appropriate permissions for writing to/reading from an external storage device have been set in your Manifest.xml file?
Also, does the code exit with any of the exceptions above? Print more illustrative messages than the stacktrace. Something like so:
try {
} catch (FileNotFoundException e) {
Log.v(this.toString(), "Exception caught in block");
}
or something on these lines..
HTH
Sriram
Problems with your code:
1) You are creating a directory with the filename. Instead try mkdir() with only the 'path'
2) Pass only 'file.getAbsolutePath()' without the "file://" to insertImage() function
3) There is an alternate api to insertImage for which you need not create one more file locally. Pass the bitmap directly to that.
Hope this helps.

Categories

Resources