Estoy usando una vista de imagen y un botón en 1 XML, y estoy recuperando las imágenes como URL de webServer y mostrándolas en ImageView. Ahora, si se hace clic en el botón (Guardar), debo guardar esa imagen en particular en la tarjeta SD. ¿Como hacer esto?
NOTA: la imagen actual debe guardarse.
Primero, necesitas obtener tu Bitmap. Ya puede tenerlo como un objeto Bitmap, o puede intentar obtenerlo desde ImageView, por ejemplo:
BitmapDrawable drawable = (BitmapDrawable) mImageView1.getDrawable(); Bitmap bitmap = drawable.getBitmap();
Luego debe acceder al directorio (un objeto File ) desde la tarjeta SD, como por ejemplo:
File sdCardDirectory = Environment.getExternalStorageDirectory();
A continuación, crea tu archivo específico para el almacenamiento de imágenes:
File image = new File(sdCardDirectory, "test.png");
Después de eso, solo tienes que escribir el bitmap gracias a su compresión de método, como por ejemplo:
boolean success = false; // Encode the file as a PNG image. FileOutputStream outStream; try { outStream = new FileOutputStream(image); bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream); /* 100 to keep full quality of the image */ outStream.flush(); outStream.close(); success = true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
Finalmente, solo trate con el resultado booleano si es necesario. Como:
if (success) { Toast.makeText(getApplicationContext(), "Image saved with success", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Error during image saving", Toast.LENGTH_LONG).show(); }
No olvide agregar el siguiente permiso en su Manifiesto:
La solución probable es
Android: guardar una imagen descargada de la URL en una tarjeta SD
Bitmap bitMapImg; void saveImage() { File filename; try { String path = Environment.getExternalStorageDirectory().toString(); new File(path + "/folder/subfolder").mkdirs(); filename = new File(path + "/folder/subfolder/image.jpg"); FileOutputStream out = new FileOutputStream(filename); bitMapImg.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); MediaStore.Images.Media.insertImage(getContentResolver(), filename.getAbsolutePath(), filename.getName(), filename.getName()); Toast.makeText(getApplicationContext(), "File is Saved in " + filename, 1000).show(); } catch (Exception e) { e.printStackTrace(); } }