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.
Related
Here's my code:
String content = mEditText.getText().toString();
FileOutputStream fos;
try {
fos = openFileOutput(title, MODE_PRIVATE);
fos.write(content.getBytes());
Toast.makeText(EditActivity.this, "Saved to "+getFilesDir() + "/" + title, Toast.LENGTH_LONG).show();
fos.close();
saved = true;
} catch (IOException e) {
Toast.makeText(EditActivity.this, "Error happened", Toast.LENGTH_SHORT).show();
}
If I run the code like this, it tells saved to /data/data/mypackagename/files/FileTitle. I want it to save the file in another directory for example save to /data/data/mypackagename/files/userData/FileTitle.I don't know any way to do this
What you need is the File constuctor that takes a parent File and a relative path to file. You've correctly established that openFileOutput() creates the file in getFilesDir(), so the code would look something like this:
FileOutputStream fos = null;
try {
final File dir = new File(getFilesDir(), "some/long/path");
dir.mkdirs();
final File file = new File(dir, "file.txt");
fos = new FileOutputStream(file);
// Use fos...
} catch (IOException e) {
// Handle error...
} finally {
if (fos != null) {
try {
fos.close()
} catch (IOException ignore) {
// Close quietly.
}
}
}
File is just a pointer, it may point to a directory, it may even point to something that's not there yet, like a new file. FileOutputStream will create a file if it doesn't exist.
If you choose to place your new file in another directory, make sure it exists first by calling mkdirs() on the directory.
I am trying to save many bitmaps in my app's folder on sdcard. However I am getting out of memory error. What is the best way to handle bitmaps and memory in this situation. Also where will I call bitmap.recycle() looking at below code? Thanks
Here is the code with which I am saving bitmaps on sdcard
Bitmap b1 = BitmapFactory.decodeResource(getResources(), R.drawable.sky);
ByteArrayOutputStream bStream1 = new ByteArrayOutputStream();
b1.compress(Bitmap.CompressFormat.PNG, 100, bStream1);
File file= new File(Environment.getExternalStorageDirectory() + File.separator + "AppName" + "/image1.png");
if(!file.exists()) {
try {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
fos.write(bStream1.toByteArray());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I think to use bitmap.recycle() and keep your code nice, you should move if(!file.exists()) into try statement, and then in finally recycle your Bitmap
try {
if(!file.exists()) {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
fos.write(bStream1.toByteArray());
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
b1.recycle()
}
Something like this.
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");
I have an image that is in the following location (it's in my android workspace resources),
D:\Android\WorkSpace\myprojectname\res\drawable-hdpi
I have used the following line of code to attach this image to an email but it doesn't seem to be working, it sends the email but it won't have the attachment.
emailIntent.putExtra(android.content.Intent.EXTRA_STREAM,Uri.parse("android.resource://com.mywebsite.myprojectname/" + R.drawable.image));
this this wrong?
Resources res = this.getResources();
Bitmap bm = BitmapFactory.decodeResource(res, R.drawable.image);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory(), "image.jpg");
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//write the bytes in file
FileOutputStream fo = null;
try {
fo = new FileOutputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Uri uri = Uri.fromFile(f);
After that,
Where u r sending the email, do the following,
intent.putExtra(Intent.EXTRA_STREAM, uri);
It will work for sure. it worked for completely. Try it.
Well, the first problem is that even if that URI format is right (which I doubt), that file would be inside your application's sandbox, which is not accessible to the E-mail activity (or any other activity, for that matter). In any case, you're gonna have to write that file into the SD card and have the email program read it from there. You can output the bitmap using the following code:
Bitmap image = BitmapFactory.decodeResource(getResources(),R.drawable.image);
File file = new File(Environment.getExternalStorageDirectory(), "forEmail.PNG");
OutputStream outStream = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
Then use Uri.fromFile() to generate the URI from the file defined above:
emailIntent.putExtra(android.content.Intent.EXTRA_STREAM, Uri.fromFile(file));
(Code for resource to file adapted from here)
The other answers might work too (they didn't work for me though)! I got it running using only the one line of code bellow, which is very simple and easy. Thanks everyone.
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://" + getPackageName() + "/" + R.drawable.image));
I think my issue was that I was putting the package name wrong, but using the getPackageName() method that issue is solved!
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" />