2010-06-14 6 views
3

J'utilise le code suivant pour afficher le bitmap dans mon ImageView. Lorsque j'essaie de charger une image de taille par exemple supérieure à 1,5 Mo cela me donne une erreur. Quelqu'un me suggère une solution?Comment gérer une erreur de mémoire insuffisante?

try { 

         URL aURL = new URL(myRemoteImages[val]); 
         URLConnection conn = aURL.openConnection(); 

         conn.connect(); 
         InputStream is = null; 
         try 
         { 
          is= conn.getInputStream(); 
         }catch(IOException e) 
         { 


          return 0; 

         } 
         int a= conn.getConnectTimeout(); 
         BufferedInputStream bis = new BufferedInputStream(is); 

         Bitmap bm; 
         try 
         { 
          bm = BitmapFactory.decodeStream(bis); 
         }catch(Exception ex) 
         { 
          bis.close(); 
          is.close(); 
          return 0; 
         } 
         bis.close(); 
         is.close(); 
         img.setImageBitmap(bm); 

        } catch (IOException e) { 
         return 0; 
        } 

        return 1; 

chat journal:

06-14 12:03:11.701: ERROR/AndroidRuntime(443): Uncaught handler: thread main exiting due to uncaught exception 
06-14 12:03:11.861: ERROR/AndroidRuntime(443): java.lang.OutOfMemoryError: bitmap size exceeds VM budget 
06-14 12:03:11.861: ERROR/AndroidRuntime(443):  at android.graphics.BitmapFactory.nativeDecodeStream(Native Method) 

Répondre

1

Vous devriez décoder avec option inSampleSize pour réduire la consommation de mémoire. Strange out of memory issue while loading an image to a Bitmap object

Une autre inJustDecodeBounds option peut vous aider à trouver la valeur correcte de inSampleSize http://groups.google.com/group/android-developers/browse_thread/thread/bd858a63563a6d4a

+0

Pour éviter des exceptions java.lang.OutOfMemory, vérifier les dimensions d'un bitmap avant le décodage, à moins que vous absolument confiance à la source pour vous fournir des données d'image de taille qui on pouvait s'y attendre confortablement dans la adapte mémoire disponible. BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource (getResources(), R.id.myimage, options); int imageHeight = options.outHauteur; int imageWidth = options.outWidth; Chaîne imageType = options.outMimeType; – hitesh141

0

En général, je pense que ce blog couvre les meilleures pratiques sur la façon de regarder l'allocation de mémoire/comment utiliser des références faibles/souples pour éviter les débordements. Hope this helps.

-2
try { 
    Bitmap bitmap=null; 

    byte[] profileImageInBytes; 

    String url="http://photo.net/learn/collage/complete-full-size.jpg"; 

    HttpGet httpRequest = null; 

    httpRequest = new HttpGet(url); 

    HttpClient httpclient = new DefaultHttpClient(); 

    HttpResponse response = (HttpResponse) httpclient.execute(httpRequest); 

    HttpEntity entity = response.getEntity(); 

    BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); 

    InputStream instream = bufHttpEntity.getContent(); 

    System.gc(); 

    Runtime.getRuntime().gc(); 

    BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options(); 
    bmpFactoryOptions.inJustDecodeBounds = true; 
    bmpFactoryOptions.inTempStorage = new byte[32 * 1024]; 
    bmpFactoryOptions.inSampleSize = 4;  
    bmpFactoryOptions.outWidth = 640;  
    bmpFactoryOptions.outHeight = 480;  
    bmpFactoryOptions.inDither=false;   
    bmpFactoryOptions.inInputShareable=true; 

    bitmap = BitmapFactory.decodeStream(instream, new Rect(), bmpFactoryOptions); 

    System.out.println("hi " +bitmap); 
    Bitmap map = Bitmap.createScaledBitmap(bitmap, 200, 200, true); 
    System.out.println("23"); 
    System.out.println("hihi hi " +map); 
    BitmapDrawable bmd = new BitmapDrawable(map); 

    System.out.println("24"); 
    System.out.println("hihi hi " +bmd); 
    ByteArrayOutputStream stream = new ByteArrayOutputStream(); 

    System.out.println(stream); 

    map.compress(Bitmap.CompressFormat.JPEG, 100, stream); 

    int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight 
    /(float) 400); 
    int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth 
    /(float) 400); 

    if (heightRatio > 1 || widthRatio > 1) { 
    if (heightRatio > widthRatio) { 
     bmpFactoryOptions.inSampleSize = heightRatio; 
    } else { 
     bmpFactoryOptions.inSampleSize = widthRatio; 
    } 
    } 

    Bundle params=new Bundle(); 
    params.putString("method", "photos.upload"); 
    profileImageInBytes = stream.toByteArray(); 
    System.out.println(profileImageInBytes); 
    System.out.println(" profile image bytes "); 
    System.out.println("Bytes : " + profileImageInBytes); 
    params.putByteArray("picture", profileImageInBytes); 
    System.out.println("My Picture : " + params); 

    mAsyncRunner.request(null, params, "POST", 
      new SampleUploadListener(), null); 
    System.out.println("Uploading"); 

} 
catch (IOException e) { 
    e.printStackTrace(); 
} 
+0

s'il vous plaît corriger votre mise en forme, aussi votre code est presque illisible –

+0

Bienvenue dans Stack Overflow! Plutôt que de publier uniquement un bloc de code, veuillez * expliquer * pourquoi ce code résout le problème posé. Sans explication, ce n'est pas une réponse. –

Questions connexes