在imageview中设置图像时出现内存不足错误?

时间:2015-04-27 07:23:03

标签: android out-of-memory android-imageview

我可以使用方法选择图像 1.使用画廊 2.使用相机 这是用于上传,所以当我使用相机拍照时,它设置在imageview但是之后如果我从图库中拍摄图像,它显示内存不足错误。我尝试了很多代码,我在下面评论过代码,但对我没什么用。

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {

        if(data.getData() != null) {

            //((BitmapDrawable)iv.getDrawable()).getBitmap().recycle();
            selectedImageUri = data.getData();
        } else {

            Log.d("selectedPath1 : ","Came here its null !");
            Toast.makeText(getApplicationContext(), "failed to get Image!", 500).show();
        }
        final BitmapFactory.Options options = new BitmapFactory.Options();
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        if (requestCode == 100 && resultCode == RESULT_OK) {

            options.inSampleSize = 8;
            /* if(photo!=null) {
                photo.recycle();
                photo=null;
            }*/
            selectedPath = getPath(selectedImageUri);
            iv.setImageURI(selectedImageUri);
        } 

        if (requestCode == 10) {

            options.inSampleSize = 8;
            /*iv.clearAnimation();
            if(photo!=null) {

                photo.recycle();
                photo=null;
            }*/

            selectedPath = getPath(selectedImageUri);
            // ((BitmapDrawable)iv.getDrawable()).getBitmap().recycle();
            iv.setImageURI(selectedImageUri);
        }
    }

    protected void onDestroy() {

        // TODO Auto-generated method stub
        super.onDestroy();

        iv.setImageDrawable(null);
        // Dismiss the progress bar when application is closed
        if (prgDialog != null) {

            prgDialog.dismiss();
        }
    }

3 个答案:

答案 0 :(得分:2)

您需要优化位图加载,Android开发者上有一个非常好的article,可以解释如何正确地进行加载。

答案 1 :(得分:0)

您正在使用BitmapFactory.Options但未将其应用于图片获取器:

你应该需要这样的东西:

InputStream input = this.getContentResolver().openInputStream(uri);

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

    Bitmap bitmap = BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
    input.close();

希望有所帮助

答案 2 :(得分:0)

你试试这个我只是在我的应用程序注册表中执行此代码

// Image Purpose
String selectedImagePath, ServerUploadPath = "" + "", str_response;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int SELECT_PICTURE = 1;
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
static File mediaFile;
private Uri fileUri; // file url to store image/video
boolean ChangeButton = true, btnChangePic = false;
// ImageView DefaultImage;
Bitmap DefaultImage;
Bitmap rotatedBMP;
public void cameraAndGalaryPicture() {
    final String[] opString = { "Take Photo", "Choose From Gallery",
            "Cancel" };

    AlertDialog.Builder dbuilder = new AlertDialog.Builder(
            SignUp_Activity.this);
    dbuilder.setTitle("Add Photo!");

    dbuilder.setItems(opString, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (opString[which].equals("Take Photo")) {
                fromCamera();
            } else if (opString[which].equals("Choose From Gallery")) {
                fromFile();
            } else {
                dialog.dismiss();
            }

        }
    });

    dbuilder.show();
}

public void fromCamera() {

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

}

public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
                    + IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());

    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else {
        return null;
    }
    Log.e("path", "media file:-" + mediaFile);
    return mediaFile;
}

public void fromFile() {

    Intent intent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    intent.setType("image/*");
    startActivityForResult(Intent.createChooser(intent, "Select File"),
            SELECT_PICTURE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == this.RESULT_OK) {

        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
            System.out.println("Image Path : " + selectedImagePath);
            Log.d("select pah", "path" + selectedImagePath);
            previewCapturedImage();
        }

    }
    // if the result is capturing Image
    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        if (resultCode == this.RESULT_OK) {
            // successfully captured the image
            // display it in image view
            selectedImagePath = mediaFile.toString();
            previewCapturedImage();
        } else if (resultCode == this.RESULT_CANCELED) {
            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to capture image
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = this.managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

private void previewCapturedImage() {
    try {

        int targetW = 380;
        int targetH = 800;
        Log.d("Get w", "width" + targetW);
        Log.d("Get H", "height" + targetH);
        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(selectedImagePath, bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor << 1;
        bmOptions.inPurgeable = true;
        Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath,
                bmOptions);

        Matrix mtx = new Matrix();

        try {

            File imageFile = new File(selectedImagePath);

            ExifInterface exif = new ExifInterface(
                    imageFile.getAbsolutePath());
            int orientation = exif.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            Log.e("Orintation", "  :-" + orientation);
            switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_270:

                mtx.postRotate(270);
                rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
                        bitmap.getWidth(), bitmap.getHeight(), mtx, true);
                if (rotatedBMP != bitmap)
                    bitmap.recycle();
                iv_SelectPhoto.setImageBitmap(rotatedBMP);
                Global.rg_image = rotatedBMP;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:

                mtx.postRotate(180);
                rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
                        bitmap.getWidth(), bitmap.getHeight(), mtx, true);
                if (rotatedBMP != bitmap)
                    bitmap.recycle();
                iv_SelectPhoto.setImageBitmap(rotatedBMP);
                Global.rg_image = rotatedBMP;
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:

                mtx.postRotate(90);
                rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
                        bitmap.getWidth(), bitmap.getHeight(), mtx, true);
                if (rotatedBMP != bitmap)
                    bitmap.recycle();
                iv_SelectPhoto.setImageBitmap(rotatedBMP);
                Global.rg_image = rotatedBMP;
                break;
            case ExifInterface.ORIENTATION_NORMAL:

                mtx.postRotate(0);
                rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
                        bitmap.getWidth(), bitmap.getHeight(), mtx, true);
                if (rotatedBMP != bitmap)
                    bitmap.recycle();
                iv_SelectPhoto.setImageBitmap(rotatedBMP);
                Global.rg_image = rotatedBMP;
                break;
            default:
                mtx.postRotate(0);
                rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
                        bitmap.getWidth(), bitmap.getHeight(), mtx, true);
                if (rotatedBMP != bitmap)
                    bitmap.recycle();
                iv_SelectPhoto.setImageBitmap(rotatedBMP);
                // img_profilepic.setImageBitmap(BitmapFactory
                // .decodeFile(mCurrentPhotoPath));
                Global.rg_image = rotatedBMP;

            }

            Log.i("RotateImage", "Exif orientation: " + orientation);

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

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

rg_image用于在我的应用程序中将图像存储在Global类中。