2011-11-20 23 views
6

Creo que hay un problema con mi ImageView. creé una galería, donde puedo tocar una imagen y ponerla en mi ImageView a continuación:Poner una imagen grande en una ImageView no funciona

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:background="@drawable/fonddegrade"> 

<Gallery android:layout_height="wrap_content" 
    android:id="@+id/gallery" 
    android:layout_width="fill_parent" /> 

<ImageView android:layout_below="@+id/gallery" 
    android:layout_height="wrap_content" 
    android:id="@+id/laphoto" 
    android:layout_width="wrap_content" 
    android:layout_centerHorizontal="true"/> 

Esto es perfectamente trabajando con una imagen pequeña, pero no con la imagen grande (3264 * 1952). Cuando lo toco (así que, tratando de ponerlo en ImageView), tengo un error y la aplicación se bloquea. Aquí está mi código java para mostrar la imagen:

 public void onCreate(Bundle savedInstanceState) { 

      super.onCreate(savedInstanceState); 
      this.requestWindowFeature(Window.FEATURE_NO_TITLE); 
      setContentView(R.layout.photo); 

      File images; // Trouver le bon endroit de stockage 
      if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) 
       images = new File("/sdcard/MyPerformance/Photo"); 
      else 
       images = this.getFilesDir(); 

      images.mkdirs(); 
      File[] imagelist = images.listFiles(new FilenameFilter(){ 
       @Override 
       public boolean accept(File dir, String name) 
       { 
        return ((name.endsWith(".jpg"))||(name.endsWith(".png"))); 
       } 
      }); 

      mFiles = new String[imagelist.length]; 
      for(int i = 0 ; i< imagelist.length; i++) 
      { 
       mFiles[i] = imagelist[i].getAbsolutePath(); 
      } 
      mUrls = new Uri[mFiles.length]; 
      for(int i = 0; i < mFiles.length; i++) 
      { 
       mUrls[i] = Uri.parse(mFiles[i]);  
      } 

      imgView = (ImageView)findViewById(R.id.laphoto); 
      if(mFiles.length != 0) 
       imgView.setImageURI(mUrls[0]); 

      gallery = (Gallery) findViewById(R.id.gallery); 
      gallery.setAdapter(new ImageAdapter(this)); 

      gallery.setOnItemClickListener(new OnItemClickListener() { 
       @Override 
       public void onItemClick(AdapterView<?> parent, View v, int position, long id) { 
        imgView.setImageURI(mUrls[position]); 
       } 
      }); 
    } 

O bien el problema viene del setImageURI (pero no creo que esta es la causa, ya que es un trabajo con una imagen pequeña) o debido al tamaño de la imagen.

¿Qué solución me puede dar para resolver este problema? Tienes mis gracias.

PD: ¿Por qué mi "Hola" siempre se eliminan?

+0

Entonces, ¿cuál es el problema? ¿Se cuelga? Por cierto, tu imagen se ve muy grande, Android podría quedar sin memoria mientras se carga. –

+0

Pre-cambiar el tamaño de la imagen, este es bastante cerdo. Un producto comercial es http://www.avs4you.com/AVS-Image-Converter.aspx – mozillanerd

+0

Además, si solo comprueba el error de bloqueo en logcat, ¿le dará una pista? Haga eso y publique el error si aún tiene dudas. – Peterdk

Respuesta

8

Tu imagen es probablemente demasiado grande para Android y se queda sin memoria. Las aplicaciones pueden tener tan solo 16 MB de memoria utilizable. Su imagen toma 3264 * 1952 * 4 = ~ 25.5Mb (ancho altura argb). Así que podría ser mejor cambiar el tamaño de las imágenes en un tamaño más pequeño.

Ver: http://android-developers.blogspot.co.uk/2009/01/avoiding-memory-leaks.html
continuación: Strange out of memory issue while loading an image to a Bitmap object
Por último: VM running out of memory while getting images from the cache

+2

¡Esto es todo! Sus enlaces me ayudaron mucho, mi problema era el mismo que el segundo, y usé la misma solución para deshacerme de ese problema. Entonces, tenemos que escalar una imagen demasiado grande para un buen funcionamiento. – FR073N

+0

Me alegra que hayan funcionado :) Parecía un problema similar. –

+0

(Recuerde también aceptar la respuesta también) –

1

Aquí está un mapa de bits [util clase para ayudarle con el manejo de los mapas de bits grandes.

import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 

public class BitmapUtils { 

    public static int calculateInSampleSize(
      BitmapFactory.Options options, int reqWidth, int reqHeight) { 
    // Raw height and width of image 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 

    if (height > reqHeight || width > reqWidth) { 

     // Calculate ratios of height and width to requested height and width 
     final int heightRatio = Math.round((float) height/(float) reqHeight); 
     final int widthRatio = Math.round((float) width/(float) reqWidth); 

     // Choose the smallest ratio as inSampleSize value, this will guarantee 
     // a final image with both dimensions larger than or equal to the 
     // requested height and width. 
     inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; 

    } 

    return inSampleSize; 
} 


    public static Bitmap decodeSampledBitmapFromResource(String pathToFile, 
       int reqWidth, int reqHeight) { 

     // First decode with inJustDecodeBounds=true to check dimensions 
     final BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     BitmapFactory.decodeFile(pathToFile, options); 

     // Calculate inSampleSize 
     options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

     // Decode bitmap with inSampleSize set 
     options.inJustDecodeBounds = false; 
     return BitmapFactory.decodeFile(pathToFile, options); 
    } 

} 
0

He buscado durante horas y pasado por todos los enlaces y finalmente encontré esto.

Glide.with (getContext()) .load (selectedImageUri) .into (imageView);

y glide hace todo el trabajo de back-end. Me hizo el día.

Glide Github Enlace: https://github.com/bumptech/glide

+0

Si bien este enlace puede responder a la pregunta, solo se desalientan las respuestas del enlace en Stack Overflow, puede mejorar esta respuesta tomando partes vitales del enlace y poniéndolo en su respuesta, esto asegura su respuesta sigue siendo una respuesta si el enlace se cambia o elimina :) – WhatsThePoint

Cuestiones relacionadas