วิธีหลีกเลี่ยงข้อผิดพลาดหน่วยความจำไม่เพียงพอขณะจัดการ Imageviews

ในแอปของฉัน ฉันกำลังเลือกรูปภาพจากที่เก็บข้อมูลหรือถ่ายภาพโดยใช้กล้อง และรูปภาพจะตั้งค่าเป็นมุมมองรูปภาพ เมื่อทำสิ่งนี้ ฉันได้รับข้อผิดพลาดหน่วยความจำไม่เพียงพอ เพื่อหลีกเลี่ยงปัญหานี้ ฉันใช้วิธีนี้ แต่มันไม่ทำงาน ใครสามารถช่วยแก้ไขปัญหานี้ได้ หรือใครสามารถแนะนำวิธีอื่นเพื่อจัดการกับปัญหานี้ได้

 public void decodeFile(String filePath) {
    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);

    // The new size we want to scale to
    final int REQUIRED_SIZE = 1024;

    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }

    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    bitmap = BitmapFactory.decodeFile(filePath, o2);

    imgView.setImageBitmap(bitmap);

}

person Jack    schedule 08.07.2015    source แหล่งที่มา
comment
ดูเหมือนว่าคุณกำลังเรียก BitmapFactory.decodeFile สองครั้ง ซึ่งจะโหลดภาพของคุณเข้าสู่หน่วยความจำสองครั้ง ดูที่: stackoverflow.com/questions/11681274/   -  person Morrison Chang    schedule 08.07.2015
comment
ฉันได้รับโค้ดนี้จากบทช่วยสอน คุณสามารถตรวจสอบคำสั่ง if นี้ได้ และโปรดทำให้ถูกต้องหากมีข้อผิดพลาด ฉันไม่สามารถเข้าใจคำสั่งนี้ได้หาก (width_tmp REQUIRED_SIZE height_tmp REQUIRED_SIZE) พัง   -  person Jack    schedule 08.07.2015
comment
o.inJustDecodeBounds = เท็จ; เพิ่มสิ่งนี้ก่อน BitmapFactory.Options o2 = new BitmapFactory.Options();   -  person Piyush    schedule 08.07.2015


คำตอบ (1)


ฉันขอแนะนำให้ใช้ไลบรารีเพื่อจัดการการโหลด การแคช และการแสดงรูปภาพ ใช้งานง่ายและคุณไม่จำเป็นต้องดูแลการลดขนาดรูปภาพ ฯลฯ

ในโครงการของฉัน ฉันใช้ Universal Image Loader โดย nostra13 มันค่อนข้างใช้งานง่ายและมีคุณสมบัติมากมาย เช่น หน่วยความจำและการแคชดิสก์ คุณควรลองดู

person W3hri    schedule 08.07.2015