Android – Enregistrer l’image de l’URL sur la carte SD

Je souhaite enregistrer une image d’une URL sur la carte SD (pour une utilisation ultérieure), puis la charger à partir de la carte SD afin de l’utiliser en tant que superposition amovible pour Google Maps.

Voici la section de sauvegarde de la fonction:

//SAVE TO FILE Ssortingng filepath = Environment.getExternalStorageDirectory().getAbsolutePath(); Ssortingng extraPath = "/Map-"+RowNumber+"-"+ColNumber+".png"; filepath += extraPath; FileOutputStream fos = null; fos = new FileOutputStream(filepath); bmImg.compress(CompressFormat.PNG, 75, fos); //LOAD IMAGE FROM FILE Drawable d = Drawable.createFromPath(filepath); return d; 

L’image est enregistrée avec succès sur la carte SD, mais échoue lors de l’obtention de la ligne createFromPath() . Je ne comprends pas pourquoi cela sauverait bien cette destination mais ne se chargerait pas d’elle ….

Essayez ce code.Il fonctionne …

 try { URL url = new URL("Enter the URL to be downloaded"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.connect(); File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile(); Ssortingng filename="downloadedFile.png"; Log.i("Local filename:",""+filename); File file = new File(SDCardRoot,filename); if(file.createNewFile()) { file.createNewFile(); } FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = urlConnection.getInputStream(); int totalSize = urlConnection.getContentLength(); int downloadedSize = 0; byte[] buffer = new byte[1024]; int bufferLength = 0; while ( (bufferLength = inputStream.read(buffer)) > 0 ) { fileOutput.write(buffer, 0, bufferLength); downloadedSize += bufferLength; Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ; } fileOutput.close(); if(downloadedSize==totalSize) filepath=file.getPath(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { filepath=null; e.printStackTrace(); } Log.i("filepath:"," "+filepath) ; return filepath; 

DownloadManager fait tout cela pour vous.

 public void downloadFile(Ssortingng uRl) { File direct = new File(Environment.getExternalStorageDirectory() + "/AnhsirkDasarp"); if (!direct.exists()) { direct.mkdirs(); } DownloadManager mgr = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE); Uri downloadUri = Uri.parse(uRl); DownloadManager.Request request = new DownloadManager.Request( downloadUri); request.setAllowedNetworkTypes( DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE) .setAllowedOverRoaming(false).setTitle("Demo") .setDescription("Something useful. No, really.") .setDestinationInExternalPublicDir("/AnhsirkDasarpFiles", "fileName.jpg"); mgr.enqueue(request); // Open Download Manager to view File progress Toast.makeText(getActivity(), "Downloading...",Toast.LENGTH_LONG).show(); startActivity(Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)); } 

Essayez ce code pour enregistrer l’image de l’URL sur la carte SD.

 URL url = new URL ("file://some/path/anImage.png"); InputStream input = url.openStream(); try { File storagePath = Environment.getExternalStorageDirectory(); OutputStream output = new FileOutputStream (storagePath, "myImage.png"); try { byte[] buffer = new byte[aReasonableSize]; int bytesRead = 0; while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) { output.write(buffer, 0, bytesRead); } } finally { output.close(); } } finally { input.close(); } 

Si vous souhaitez créer un sous-répertoire sur la carte SD, utilisez:

 File storagePath = new File(Environment.getExternalStorageDirectory(),"Wallpaper"); storagePath.mkdirs(); 

Pour créer un sous-répertoire “/ sdcard / Wallpaper /”.

J’espère que cela vous aidera.

Prendre plaisir. 🙂

J’ai également fait face au même problème et résolu le mien avec cela. Essaye ça

 private class ImageDownloadAndSave extends AsyncTask { @Override protected Bitmap doInBackground(Ssortingng... arg0) { downloadImagesToSdCard("",""); return null; } private void downloadImagesToSdCard(Ssortingng downloadUrl,Ssortingng imageName) { try { URL url = new URL(img_URL); /* making a directory in sdcard */ Ssortingng sdCard=Environment.getExternalStorageDirectory().toSsortingng(); File myDir = new File(sdCard,"test.jpg"); /* if specified not exist create new */ if(!myDir.exists()) { myDir.mkdir(); Log.v("", "inside mkdir"); } /* checks the file and if it already exist delete */ Ssortingng fname = imageName; File file = new File (myDir, fname); if (file.exists ()) file.delete (); /* Open a connection */ URLConnection ucon = url.openConnection(); InputStream inputStream = null; HttpURLConnection httpConn = (HttpURLConnection)ucon; httpConn.setRequestMethod("GET"); httpConn.connect(); if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) { inputStream = httpConn.getInputStream(); } FileOutputStream fos = new FileOutputStream(file); int totalSize = httpConn.getContentLength(); int downloadedSize = 0; byte[] buffer = new byte[1024]; int bufferLength = 0; while ( (bufferLength = inputStream.read(buffer)) >0 ) { fos.write(buffer, 0, bufferLength); downloadedSize += bufferLength; Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ; } fos.close(); Log.d("test", "Image Saved in sdcard.."); } catch(IOException io) { io.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } } } 

Déclarez vos opérations réseau dans AsyncTask, car elles seront chargées en tâche de fond. Ne chargez pas d’opération réseau sur le thread principal. Après cela, en cliquant sur le bouton ou en vue du contenu, appelez cette classe comme

  new ImageDownloadAndSave().execute(""); 

Et n’oubliez pas d’append l’autorisation nework en tant que:

   

J’espère que cela pourra aider quelqu’un 🙂

Je crois que cela échoue parce que vous écrivez une version compressée du bitmap dans le stream de sortie, qui devrait être chargé avec BitmapFactory.decodeStream() . Jetez un coup d’œil à la documentation à ce sujet.

Si vous avez besoin d’un Drawable ( decodeStream() renvoie un Bitmap ), appelez simplement Drawable d = new BitmapDrawable(bitmap) .

Essayez ce code..Il fonctionne bien

 public static Bitmap loadImageFromUrl(Ssortingng url) { URL m; InputStream i = null; BufferedInputStream bis = null; ByteArrayOutputStream out =null; try { m = new URL(url); i = (InputStream) m.getContent(); bis = new BufferedInputStream(i,1024 * 8); out = new ByteArrayOutputStream(); int len=0; byte[] buffer = new byte[1024]; while((len = bis.read(buffer)) != -1){ out.write(buffer, 0, len); } out.close(); bis.close(); } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } byte[] data = out.toByteArray(); Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); //Drawable d = Drawable.createFromStream(i, "src"); return bitmap; } 

et enregistrez le bitmap dans le répertoire

 ByteArrayOutputStream bytes = new ByteArrayOutputStream(); _bitmap.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(); 

et n’oubliez pas d’append l’autorisation de manifester

  

Essayez ceci … Un moyen facile d’accomplir la tâche.

 Picasso.with(getActivity()) .load(url) .into(new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { try { Ssortingng root = Environment.getExternalStorageDirectory().toSsortingng(); File myDir = new File(root + "/yourDirectory"); if (!myDir.exists()) { myDir.mkdirs(); } Ssortingng name = new Date().toSsortingng() + ".jpg"; myDir = new File(myDir, name); FileOutputStream out = new FileOutputStream(myDir); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); } catch(Exception e){ // some action } } @Override public void onBitmapFailed(Drawable errorDrawable) { } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } } );