2 votes

Télécharger l'image et la stocker dans le dossier sdcard

Je veux télécharger une image à partir d'une url et la stocker dans le dossier de la carte SD.
Si le dossier n'existe pas, créez un dossier et enregistrez-le.
Mais il donne l'exception suivante :

java.io.FileNotFoundException: /mnt/sdcard (Is a directory)

2voto

RobGThai Points 2314

Le message est clair. /mnt/sdcard est un répertoire et non un fichier. Vous devez créer FileOutputStream qui écrit dans un non répertoire chemin.

Par exemple :

//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){}
}

2voto

Khan Points 3274

Essayez quelque chose comme ceci

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();

      }
  }

où les méthodes sont les suivantes

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;
 }

1voto

Caner Points 15625

Vous donnez un mauvais chemin d'accès lorsque vous essayez de sauvegarder l'image. Il semble que vous utilisiez "/mnt/sdcard" alors qu'il devrait s'agir de quelque chose comme "/mnt/sdcard/image.jpg"

1voto

Furqi Points 1649
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;
}

1voto

osayilgan Points 2275

Essayez celui-ci, qui renverra la mémoire externe si elle existe, sinon il renverra le répertoire de la mémoire du téléphone. Le constructeur prend en paramètre Context et le nom du dossier que vous voulez créer. Essayez aussi ce lien, c'est assez intéressant pour ce dont vous avez besoin. Chargeur d'images

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();
}
}

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X