2013-10-09 90 views
9

我一個代碼示例的工作,我必須從圖庫中選擇圖像的代碼工作,但是從圖片庫圖片的選擇後,我得到的OutOfMemoryErrorOnActivityResult的Android從圖庫中選擇圖像顯示內存錯誤

我能夠獲得小圖像,但大圖像造成問題。

這裏是我的代碼:

try{ 
        Uri selectedImageUri = data.getData(); 
        String[] filePathColumn = {MediaStore.Images.Media.DATA}; 
        Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null); 
        cursor.moveToFirst(); 
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
        String filePath = cursor.getString(columnIndex); 
        cursor.close(); 
        bitmap = BitmapFactory.decodeFile(filePath); 
        _profileImage.setImageBitmap(bitmap); 
        _profileImage.setScaleType(ScaleType.FIT_XY); 
        Constant._addPhotoBitmap=bitmap; 
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
        Bitmap resizedbitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true); 
        resizedbitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); 
        byte [] _byteArray = baos.toByteArray(); 
        String base64 = Base64.encodeToString(_byteArray,Base64.DEFAULT); 
        Constant._addPhotoBase64 = base64; 
       }catch (OutOfMemoryError e) { 
        e.printStackTrace(); 
        Constant.showAlertDialog(Constant.errorTitle, 
          "Image size is too large.Please upload small image.", 
          DriverProfileScreen.this, false); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 

回答

11

您的文件基於其URI path..thats deirectly解碼爲什麼它被扔exception..before裝圖像設置一些options..this將減少對圖像loading..Use此方法用於加載圖像任何你想要的大小內存..

/** 
* returns the thumbnail image bitmap from the given url 
* 
* @param path 
* @param thumbnailSize 
* @return 
*/ 
private Bitmap getThumbnailBitmap(final String path, final int thumbnailSize) { 
    Bitmap bitmap; 
    BitmapFactory.Options bounds = new BitmapFactory.Options(); 
    bounds.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(path, bounds); 
    if ((bounds.outWidth == -1) || (bounds.outHeight == -1)) { 
     bitmap = null; 
    } 
    int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight 
      : bounds.outWidth; 
    BitmapFactory.Options opts = new BitmapFactory.Options(); 
    opts.inSampleSize = originalSize/thumbnailSize; 
    bitmap = BitmapFactory.decodeFile(path, opts); 
    return bitmap; 
} 
+0

感謝兄弟,現在正在工作。 –

0

一般來說android的設備堆大小隻有16MB(根據設備/操作系統的不同,可以查看post Heap Sizes),如果你正在加載圖片並且它跨越了16MB的大小,它會拋出內存異常,而不是使用用於從SD卡或從資源或甚至從網絡加載圖像的位圖嘗試使用getImageUri,加載位圖需要更多內存,或者如果您的工作使用該位圖,則可以將位圖設置爲null。

所以,你需要使用下面的代碼來縮減你的圖像:

public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){ 
try { 
    //Decode image size 
    BitmapFactory.Options o = new BitmapFactory.Options(); 
    o.inJustDecodeBounds = true; 
    BitmapFactory.decodeStream(new FileInputStream(f),null,o); 
    //The new size we want to scale to 
    final int REQUIRED_WIDTH=WIDTH; 
    final int REQUIRED_HIGHT=HIGHT; 
    //Find the correct scale value. It should be the power of 2. 
    int scale=1; 
    while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT) 
     scale*=2; 
    //Decode with inSampleSize 
    BitmapFactory.Options o2 = new BitmapFactory.Options(); 
    o2.inSampleSize=scale; 
    return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); 
} catch (FileNotFoundException e) {} 
return null; 
} 
0

規模的位圖,然後再加載它。它會解決問題。

您可以使用下面的方法來做到這一點。

private Bitmap getScaledBitmap(Uri uri){ 
     Bitmap thumb = null ; 
     try { 
      ContentResolver cr = getContentResolver(); 
      InputStream in = cr.openInputStream(uri); 
      BitmapFactory.Options options = new BitmapFactory.Options(); 
      options.inSampleSize=8; 
      thumb = BitmapFactory.decodeStream(in,null,options); 
     } catch (FileNotFoundException e) { 
      Toast.makeText(PhotoTake.this , "File not found" , Toast.LENGTH_SHORT).show(); 
     } 
     return thumb ; 
    } 

希望它有幫助。

0

試試這個代碼:

import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 

import android.app.ActivityManager; 
import android.content.ComponentCallbacks; 
import android.content.Context; 
import android.content.res.Configuration; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.AsyncTask; 
import android.support.v4.util.LruCache; 
import android.widget.ImageView; 

public class UserImageLoaderWithCache implements ComponentCallbacks { 
private KCLruCache cache; 

public UserImageLoaderWithCache(Context context) { 
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 
int memoryClass = am.getMemoryClass() * 1024 * 1024; 
cache = new KCLruCache(memoryClass); 
} 

public void display(String url, ImageView imageview, int defaultresource) { 
imageview.setImageResource(defaultresource); 
Bitmap image = cache.get(url); 
if (image != null) { 
imageview.setImageBitmap(image); 
} 
else { 
new SetImageTask(imageview).execute(url); 
} 
} 

private class KCLruCache extends LruCache<String, Bitmap> { 

public KCLruCache(int maxSize) { 
super(maxSize); 
} 
} 

private class SetImageTask extends AsyncTask<String, Void, Integer> { 
private ImageView imageview; 
private Bitmap bmp; 

public SetImageTask(ImageView imageview) { 
this.imageview = imageview; 
} 

@Override 
protected Integer doInBackground(String... params) { 
String url = params[0]; 
try { 
bmp = getBitmapFromURL(url); 
if (bmp != null) { 
cache.put(url, bmp); 
} else { 
return 0; 
} 
} catch (Exception e) { 
e.printStackTrace(); 
return 0; 
} catch (OutOfMemoryError o) { 
o.printStackTrace(); 
return 0; 
} 
return 1; 
} 

@Override 
protected void onPostExecute(Integer result) { 
if (result == 1) { 
imageview.setImageBitmap(bmp); 
} 
super.onPostExecute(result); 
} 

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

public void onLowMemory() { 
} 

/*public void onTrimMemory(int level) { 
if (level >= TRIM_MEMORY_MODERATE) { 
cache.evictAll(); 
} 
else if (level >= TRIM_MEMORY_BACKGROUND) { 
cache.trimToSize(cache.size()/2); 
} 
}*/ 

public void onConfigurationChanged(Configuration arg0) { 
// TODO Auto-generated method stub 

} 
} 
0

我用下面的代碼,並使用位圖在本地存儲空間來存儲調整Image和它的工作般的魅力

final BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inSampleSize = 8; 

     Bitmap b = BitmapFactory.decodeFile(path, options); 

這裏的路徑是圖像中StringUri路徑

相關問題