mis instasaver instasave imagenes guardar galeria fotos desde descargar como celular aplicaciones album android

android - instasaver - instasave apk



El mejor método para descargar imágenes desde la url en Android (9)

Agregue esta dependencia para redes Android en su proyecto

compilar ''com.amitshekhar.android:android-networking:1.0.0''

String url = "http://ichef.bbci.co.uk/onesport/cps/480/cpsprodpb/11136/production/_95324996_defoe_rex.jpg"; File file; String dirPath, fileName; Button downldImg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialization Of DownLoad Button downldImg = (Button) findViewById(R.id.DownloadButton); // Initialization Of DownLoad Button AndroidNetworking.initialize(getApplicationContext()); //Folder Creating Into Phone Storage dirPath = Environment.getExternalStorageDirectory() + "/Image"; fileName = "image.jpeg"; //file Creating With Folder & Fle Name file = new File(dirPath, fileName); //Click Listener For DownLoad Button downldImg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AndroidNetworking.download(url, dirPath, fileName) .build() .startDownload(new DownloadListener() { @Override public void onDownloadComplete() { Toast.makeText(MainActivity.this, "DownLoad Complete", Toast.LENGTH_SHORT).show(); } @Override public void onError(ANError anError) { } }); } }); } }

Después de ejecutar este código, compruebe la memoria del teléfono, puede ver allí una carpeta, compruebe la imagen, dentro de esta carpeta, vea allí un archivo de imagen con el nombre de "image.jpeg".

Gracias !!!

Estoy usando el siguiente método para descargar una sola imagen desde la URL

public static Bitmap getBitmap(String url) { try { InputStream is = (InputStream) new URL(url).getContent(); Bitmap d = BitmapFactory.decodeStream(is); is.close(); return d; } catch (Exception e) { return null; } }

A veces recibo una excepción de memoria.

No puedo entender la excepción de memoria. La aplicación se cerrará. ¿Cómo prevenir esto?

¿Existe un método mejor para descargar imágenes que también sea más rápido?


Intenta usar esto:

public Bitmap getBitmapFromURL(String src) { try { java.net.URL url = new java.net.URL(src); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); return myBitmap; } catch (IOException e) { e.printStackTrace(); return null; } }

Y para el problema OutOfMemory:

public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) { int width = bm.getWidth(); int height = bm.getHeight(); float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // CREATE A MATRIX FOR THE MANIPULATION Matrix matrix = new Matrix(); // RESIZE THE BIT MAP matrix.postScale(scaleWidth, scaleHeight); // "RECREATE" THE NEW BITMAP Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false); return resizedBitmap; }



Todavía estoy aprendiendo Android, por lo que no puedo proporcionar un contexto enriquecedor o una razón para mi sugerencia, pero esto es lo que estoy usando para recuperar archivos de https y URL locales. Estoy usando esto en mi resultado de onActivity (tanto para tomar fotos como para seleccionar de la galería), así como en una AsyncTask para recuperar las URL de https.

InputStream input = new URL("your_url_string").openStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input);



puede descargar imágenes por Asyn task use esta clase:

public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> { private final WeakReference<ImageView> imageViewReference; private final MemoryCache memoryCache; private final BrandItem brandCatogiriesItem; private Context context; private String url; public ImageDownloaderTask(ImageView imageView, String url, Context context) { imageViewReference = new WeakReference<ImageView>(imageView); memoryCache = new MemoryCache(); brandCatogiriesItem = new BrandItem(); this.url = url; this.context = context; } @Override protected Bitmap doInBackground(String... params) { return downloadBitmap(params[0]); } @Override protected void onPostExecute(Bitmap bitmap) { if (isCancelled()) { bitmap = null; } if (imageViewReference != null) { ImageView imageView = imageViewReference.get(); if (imageView != null) { if (bitmap != null) { memoryCache.put("1", bitmap); brandCatogiriesItem.setUrl(url); brandCatogiriesItem.setThumb(bitmap); // BrandCatogiriesItem.saveLocalBrandOrCatogiries(context, brandCatogiriesItem); imageView.setImageBitmap(bitmap); } else { Drawable placeholder = imageView.getContext().getResources().getDrawable(R.drawable.placeholder); imageView.setImageDrawable(placeholder); } } } } private Bitmap downloadBitmap(String url) { HttpURLConnection urlConnection = null; try { URL uri = new URL(url); urlConnection = (HttpURLConnection) uri.openConnection(); int statusCode = urlConnection.getResponseCode(); if (statusCode != HttpStatus.SC_OK) { return null; } InputStream inputStream = urlConnection.getInputStream(); if (inputStream != null) { Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } } catch (Exception e) { Log.d("URLCONNECTIONERROR", e.toString()); if (urlConnection != null) { urlConnection.disconnect(); } Log.w("ImageDownloader", "Error downloading image from " + url); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return null; }

}

y llamar esto como:

new ImageDownloaderTask(thumbImage, item.thumbnail, context).execute(item.thumbnail);


puede usar la función de abajo para descargar la imagen de la url.

private Bitmap getImage(String imageUrl, int desiredWidth, int desiredHeight) { private Bitmap image = null; int inSampleSize = 0; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inSampleSize = inSampleSize; try { URL url = new URL(imageUrl); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); InputStream stream = connection.getInputStream(); image = BitmapFactory.decodeStream(stream, null, options); int imageWidth = options.outWidth; int imageHeight = options.outHeight; if(imageWidth > desiredWidth || imageHeight > desiredHeight) { System.out.println("imageWidth:"+imageWidth+", imageHeight:"+imageHeight); inSampleSize = inSampleSize + 2; getImage(imageUrl); } else { options.inJustDecodeBounds = false; connection = (HttpURLConnection)url.openConnection(); stream = connection.getInputStream(); image = BitmapFactory.decodeStream(stream, null, options); return image; } } catch(Exception e) { Log.e("getImage", e.toString()); } return image; }


public void DownloadImageFromPath(String path){ InputStream in =null; Bitmap bmp=null; ImageView iv = (ImageView)findViewById(R.id.img1); int responseCode = -1; try{ URL url = new URL(path);//"http://192.xx.xx.xx/mypath/img1.jpg HttpURLConnection con = (HttpURLConnection)url.openConnection(); con.setDoInput(true); con.connect(); responseCode = con.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK) { //download in = con.getInputStream(); bmp = BitmapFactory.decodeStream(in); in.close(); iv.setImageBitmap(bmp); } } catch(Exception ex){ Log.e("Exception",ex.toString()); } }


public class testCrop extends AppCompatActivity { ImageView iv; String imagePath = "https://style.pk/wp-content/uploads/2015/07/omer-Shahzad-performed-umrah-600x548.jpg"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.testcrpop); iv = (ImageView) findViewById(R.id.testCrop); imageDownload image = new imageDownload(testCrop.this, iv); image.execute(imagePath); } class imageDownload extends AsyncTask<String, Integer, Bitmap> { Context context; ImageView imageView; Bitmap bitmap; InputStream in = null; int responseCode = -1; //constructor. public imageDownload(Context context, ImageView imageView) { this.context = context; this.imageView = imageView; } @Override protected void onPreExecute() { } @Override protected Bitmap doInBackground(String... params) { URL url = null; try { url = new URL(params[0]); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoOutput(true); httpURLConnection.connect(); responseCode = httpURLConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { in = httpURLConnection.getInputStream(); bitmap = BitmapFactory.decodeStream(in); in.close(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } @Override protected void onPostExecute(Bitmap data) { imageView.setImageBitmap(data); } } }

SALIDA