I want to download image from url and store in sdcard's folder.If folder is not exist make folder and save it.But its giving following exception:
java.io.FileNotFoundException: /mnt/sdcard (Is a directory)
The message is clear. /mnt/sdcard is a directory not a file. You need to create FileOutputStream that writes to a non-directory path.
For example:
//Setting up cache directory to store the image
File cacheDir=new File(context.getCacheDir(),"cache_folder");
// Check if cache folder exists, otherwise create folder.
if(!cacheDir.exists())cacheDir.mkdirs();
// Setting up file to write the image to.
File f=new File(cacheDir, "img.png");
// Open InputStream to download the image.
InputStream is=new URL(url).openStream();
// Set up OutputStream to write data into image file.
OutputStream os = new FileOutputStream(f);
HelperUtil.CopyStream(is, os);
...
/**
* Copy all data from InputStream and write using OutputStream
* #param is InputStream
* #param os OutputStream
*/
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
try something like this
String image_URL="http://chart.apis.google.com/chart?chs=200x200&cht=qr&chl=http%3A%2F%2Fandroid-er.blogspot.com%2F";
String extStorageDirectory;
File file;
Bitmap bm;
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
file=new File(android.os.Environment.getExternalStorageDirectory(),"Your FolderName");
extStorageDirectory = Environment.getExternalStorageDirectory().toString();
}else{
file=YourActivity.this.getCacheDir();
}
if(!file.exists())
file.mkdirs();
extStorageDirectory+="Your FolderName/yourimagename.PNG";
File imageFile = new File(extStorageDirectory);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
if(bitmap!=null){
imageview.setImageBitmap(bitmap);
}else{
extStorageDirectory = Environment.getExternalStorageDirectory().toString();
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
bm = LoadImage(image_URL, bmOptions);
imageview.setImageBitmap(bm);
OutputStream outStream = null;
file=new File(android.os.Environment.getExternalStorageDirectory(),"Your FolderName");
file=new File(extStorageDirectory, "Your FolderName/yourimagename.PNG");
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
where method are as
private Bitmap LoadImage(String URL, BitmapFactory.Options options)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private InputStream OpenHttpConnection(String strURL) throws IOException{
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try{
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
}catch (Exception ex){
Log.e("error",ex.toString());
}
return inputStream;
}
You are giving wrong path when triying to save the picture. IT seems that you use "/mnt/sdcard" whereas it should be something like "/mnt/sdcard/image.jpg"
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
bm = LoadImage(image_url, bmOptions);
extStorageDirectory = Environment.getExternalStorageDirectory()
.toString() + "/image_folder";
OutputStream outStream = null;
File wallpaperDirectory = new File(extStorageDirectory);
wallpaperDirectory.mkdirs();
File outputFile = new File(wallpaperDirectory, "image.PNG");
try {
outStream = new FileOutputStream(outputFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
private Bitmap LoadImage(String URL, BitmapFactory.Options options) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private InputStream OpenHttpConnection(String strURL) throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
Try this one, that will return the External memory if it is exist, otherwise it will return the phone memory directory. The constructor takes Context and the name of the folder that you want to create as parameters. And also try this link, its quite nice stuff about what you need. Image Loader
public class FileCache {
private File cacheDir;
private String applicationDirectory = Config.applicationMainFolder;
public FileCache(Context context, String folderName){
//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(context.getExternalFilesDir(null), applicationDirectory + folderName);
else
cacheDir = new File(context.getCacheDir(), applicationDirectory + folderName);
if(!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url){
String filename=String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
return f;
}
public void clear(){
File[] files=cacheDir.listFiles();
if(files==null)
return;
for(File f:files)
f.delete();
}
}
use this
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
File file=new File(Environment.getExternalStorageDirectory()+path);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100, bytes);
byte b[] = bytes.toByteArray();
try
{
FileOutputStream fos = new FileOutputStream(file);
fos.write(b);
fos.flush();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
path will be your folder in sdcard and bitamp is object of image
Related
I want to download an image from the given url. the downloaded image should save in SD card. I have used the below code.
URL newurl = null;
try {
newurl = new URL(strHitRes);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection = (HttpURLConnection) newurl.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".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);
Toast.makeText(getApplicationContext(),"download successful",Toast.LENGTH_LONG).show();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
But image is not downloading. Even i tested in debug mode, i found that my bitmap is null. How to solve this.
Say thanks to Vineet for his answer
try {
URL url = new URL("url from apk file is to be downloaded");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "filename.ext");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//To download bitmap from URL
public Bitmap getbmpfromURL(String surl){
try {
URL url = new URL(surl);
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
urlcon.setDoInput(true);
urlcon.connect();
InputStream in = urlcon.getInputStream();
Bitmap mIcon = BitmapFactory.decodeStream(in);
return mIcon;
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
return null;
}
}
To save bitmap to SD card
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
String fname = "Image.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();
}
}
And don't forget to use below permission in your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
Hi i have downloaded a image from a URL and written it as a bitmap to a file. I'm trying to retrieve the bitmap from the file and display it. Does anyone know how to do this? heres what i have tried it doesn't error but it doesn't display the image.
Global.java
public static void saveBitmapToFile(Context activityContext, Bitmap bitmap, String FileName){
try{
File file = new File(FileName);
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();}
catch (Exception e) {
e.printStackTrace();
Log.i(null, "Save file error!");
}
}
public static Bitmap returnBitmapFromFile(Context activityContext, String FileName){
Bitmap bitmap = BitmapFactory.decodeFile(FileName);
return bitmap;
}
GetBitmap.java
public void downloadUserPhoto(){
String userPhotoUrl = "http://static.bbci.co.uk/h4discoveryzone/ic/newsimg/media/images/229/129/68805000/jpg/_68805145_pahs2.jpg"
userPhoto = Global.createBitmapFromUrl(this, userPhotoUrl);
Global.saveBitmapToFile(this, userPhoto, "user_photo");
}
public void getUserPhoto(){
loadingText.setText("Getting User Pictures...");
Bitmap setUserPhoto = Global.returnBitmapFromFile(this, "user_photo");
logo.setImageBitmap(setUserPhoto);
}
Try to open it by using FileInputStream:
public static Bitmap returnBitmapFromFile(Context activityContext, String FileName){
FileInputStream in = new FileInputStream(FileName);
BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA= new byte[buf.available()];
buf.read(bitMapA);
buf.close();
in.close();
Bitmap bitmap = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
return bitmap;
}
Other way is to use openFileInput:
public static Bitmap returnBitmapFromFile(Context activityContext, String FileName){
FileInputStream fis;
try {
fis = openFileInput(FileName);
Bitmap bitmap = BitmapFactory.decodeStream(fis);
fis.close();
return bitmap;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
I return a Bitmap object according to a url, and the code for download picture:
URL url = new URL(imageUrlStr);
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream in = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
in.close
Then I save it to sdcard. It is ok to save picture.
Now the problem is it download the picture A when use this url to access. But it now shows another B picture in SDCARD. How to solve this problem?
You can identify images by hash-code. Not a perfect solution, good for the demo
private Bitmap getBitmap(String url) {
String filename = String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try {
Bitmap bitmap = null;
InputStream is = new URL(url).openStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
/** decodes image and scales it to reduce memory consumption*/
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
return BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
}
return null;
}
Use you just need to use method "getBitmap(String)" with your desired url as String
I've searched and tried everything I found about this topic on Google and StackOverflow but I didn't find anyway to make it work.
I have this code but it throws me a FATAL EXCEPTION.
I think that, as I am an Android Rookie there's something I do wrong. Help me please ^^
public void svgPhoto() throws IOException {
String dir = Environment.getExternalStorageDirectory().toString();
OutputStream fos = null;
File file = new File(dir,"downloadImage.JPEG");
Bitmap bm =BitmapFactory.decodeFile("http://perlbal.hi-pi.com/blog-images/3278/gd/1242316719/Chat-chat.jpg");
fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bm.compress(Bitmap.CompressFormat.JPEG, 50, bos);
bos.flush();
bos.close();
public class Download extends AsyncTask
{
#Override
protected Void doInBackground(Void... params)
{
try {
URL url = new URL(imageURL);
file2 = new File(fileName);
long startTime = System.currentTimeMillis();
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file2);
fos.write(baf.toByteArray());
fos.close();
Log.d("ImageManager",
"download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
try {
File fileWithinMyDir = getApplicationContext().getFilesDir();
String PATH = fileWithinMyDir.getAbsolutePath();
Drawable d = Drawable.createFromPath(PATH.toString());
Bitmap bmp = ((BitmapDrawable) d).getBitmap();
} catch (Exception e) {
e.printStackTrace();
}
if (dialog != null) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try next code:
String dir = Environment.getExternalStorageDirectory().toString();
File outputfile = new File(dir+"/downloadImage.JPEG");
OutputStream fOut = null;
try {
fOut = new FileOutputStream(outputfile);
Bitmap bm =BitmapFactory.decodeFile("http://perlbal.hi-pi.com/blog-images/3278/gd/1242316719/Chat-chat.jpg");
bm.compress(CompressFormat.JPEG, 50, fOut);
} catch (IOException e) {
Logger.error(e.getMessage(), e);
}finally{
try {
if(fOut != null){
fOut.flush();
fOut.close();
}
} catch (IOException e) {
Logger.error(e.getMessage(), e);
}
}
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...