2011-10-21 22 views
5

Tengo un extraño problema con mi código de Android, Tengo una imagen en la variable de mapa de bits y quiero guardar ese archivo en la tarjeta SD. código I de la siguiente manera,Tienda de imagen de mapa de bits a la tarjeta SD en Android

Bitmap IMAGE // Loaded from internet servers.; 
try { 
    File _sdCard = Environment.getExternalStorageDirectory(); 
    File _picDir = new File(_sdCard, "MyDirectory"); 
    _picDir.mkdirs(); 

    File _picFile = new File(_picDir, "MyImage.jpg"); 
    FileOutputStream _fos = new FileOutputStream(_picFile); 
    IMAGE.compress(Bitmap.CompressFormat.JPEG, 100, _fos); 
    _fos.flush(); 
    _fos.close(); 
    Toast.makeText(this, "Image Downloaded", 7000).show(); 
} catch (Exception ex) { 
    ex.printStackTrace(); 
    Toast.makeText(this, ex.getMessage(), 7000).show(); 
} 

estoy usando Xperia Arco como mi dispositivo de prueba, cuando el teléfono está conectado al ordenador, el código funciona bien, que almacena la imagen y también exhibe en la galería. Pero cuando desconecto el teléfono de mi computadora y pruebo la aplicación, no guarda la imagen y no muestra ninguna excepción.

+1

Agregue usos permiso para escribir extern al almacenamiento en archivo de manifiesto. –

+0

Eso generaría probablemente una excepción, pero una buena llamada. OP, ¿hay algún mensaje útil en la salida de logcat? –

+0

BTW, estilo menor nit: aquellos que llevan '_' en los nombres de las variables no agregan nada a la legibilidad. Sé que a veces se utilizan en otros idiomas, pero no los usaría en Java. –

Respuesta

5

uso de esta función

void saveImage() { 

    String root = Environment.getExternalStorageDirectory().toString(); 
    File myDir = new File(root + "/saved_images"); 

    String fname = "Image.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); 
      out.flush(); 
      out.close(); 

    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
} 

Marque esta respuesta va a dar más detalles Android saving file to external storage

+0

Todavía tiene el mismo problema, –

+0

Cuando ejecuto la aplicación desde eclipse funciona bien, pero cuando desconecto el cable de mi computadora y carga la aplicación desde mi teléfono, no funciona correctamente. –

+0

está dando cualquier error. –

3
ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
     thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 
     //4 
     File file = new File(Environment.getExternalStorageDirectory()+File.separator +  "image.jpg"); 
     try { 
      file.createNewFile(); 
      FileOutputStream fo = new FileOutputStream(file); 
      //5 
      fo.write(bytes.toByteArray()); 
      fo.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
1
**This Code Cover the Following Topics** 

1. Save a bitmap Image on sdcard a jpeg 
2. Create a folder on sdcard 
3. Create every file Separate name 
4. Every file save with date and time 
5. Resize the image in very small size 
6. Best thing image Quality fine not effected from Resizing 


The following method is used to create an image file using the bitmap 

pública createImageFromBitmap vacío (mapa de bits bmp) {

FileOutputStream fileOutputStream = null; 
    try { 

     // create a File object for the parent directory 
     File wallpaperDirectory = new File("/sdcard/Capture/"); 
     // have the object build the directory structure, if needed. 
     wallpaperDirectory.mkdirs(); 

     //Capture is folder name and file name with date and time 
     fileOutputStream = new FileOutputStream(String.format(
       "/sdcard/Capture/%d.jpg", 
       System.currentTimeMillis())); 

     // Here we Resize the Image ... 
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
     bmp.compress(Bitmap.CompressFormat.JPEG, 100, 
       byteArrayOutputStream); // bm is the bitmap object 
     byte[] bsResized = byteArrayOutputStream.toByteArray(); 


     fileOutputStream.write(bsResized); 
     fileOutputStream.close(); 


    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
    } 
} 


    and add this in manifest 

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
+0

¡+1 funciona sin problemas! –

Cuestiones relacionadas