【问题标题】:Out of memory error while setting an image in imageview?在imageview中设置图像时出现内存不足错误?
【发布时间】:2015-04-27 07:23:02
【问题描述】:

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

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();
        }
    }

【问题讨论】:

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


    【解决方案1】:

    您需要优化位图加载,Android Developers 上有一个非常好的article 解释了如何正确执行此操作。

    【讨论】:

    • 感谢您的解决方案。我认为 largeHeap 是这件事的唯一解决方案。 +1
    【解决方案2】:

    您正在使用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();
    

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      你正在尝试这个,我在我的应用程序注册中执行此代码

      // 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 类中存储图像。

      【讨论】:

        猜你喜欢
        • 2014-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-06
        • 2017-06-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多