如何在Android中的Bitmap上解决OutOfMemoryError?

时间:2015-06-22 05:27:17

标签: android android-intent android-activity bitmap

我想在ImageView中设置图像,我正在检索第一个活动中的图像路径,并通过Intent作为字符串传递给第二个活动。在第二个活动中,我将路径设置为ImageView。它运行正常,我需要将该图片上传到服务器。所以我将路径解码为位图。它抛出一个OutOfMemoryError。如何解决这个问题?

当我使用前置摄像头时,没有任何问题。图像上传成功。问题在于设备前置摄像头拍摄的图像。这个问题的解决方案是什么?有人可以帮忙吗?

以下是将图片路径转换为字符串并通过Intent传递的代码:

 if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {


        Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, MediaStore.Images.Media.DATE_ADDED, null, "date_added ASC");
        if(cursor != null && cursor.moveToFirst())
        {
            do {
              Uri uri = Uri.parse(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)));
              photoPath = uri.toString();

            }while(cursor.moveToNext());
            cursor.close();

            try {
                Intent intent = new Intent(MainActivity.this, ImageUploadActivity.class);
                intent.putExtra("ImagePath", photoPath);
                MainActivity.this.startActivity(intent);
            }
            catch (Exception e)
            {
                Toast.makeText(MainActivity.this, "Method invoked"+photoPath, Toast.LENGTH_SHORT).show();
            }
        }

在第二项活动中接收意图:

 Intent camIntent = getIntent();
 camPicPath = camIntent.getExtras().getString("ImagePath");
 imageView = (ImageView) findViewById(R.id.imgView);
 imageView.setImageBitmap(BitmapFactory.decodeFile(camPicPath));
 Toast.makeText(getApplicationContext(),  "PATHe"+camPicPath, Toast.LENGTH_SHORT).show();
 bitmap = (BitmapFactory.decodeFile(camPicPath));

上传文件的方法:

 class ImageUploadTask extends AsyncTask<Void, Void, String> {
    @Override
    protected String doInBackground(Void... unsued) {
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost("http://11.10.11.15/test/upload.php");

            MultipartEntity entity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            byte[] data = bos.toByteArray();


          /* entity.addPart("uploaded_file", new ByteArrayBody(data,
                    "myImage.jpg"));*/

            // String newFilename= filename.concat("file");
            // newFilename=filename+newFilename;

            entity.addPart("uploaded_file", new ByteArrayBody(data,
                    filename));
          //  Log.e(TAG, "Method invoked");
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost,
                    localContext);
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(
                            response.getEntity().getContent(), "UTF-8"));

            StringBuilder builder = new StringBuilder();
            String aux = "";

            while ((aux = reader.readLine()) != null) {
                builder.append(aux);
            }

            String sResponse = builder.toString();


            return sResponse;
        } catch (Exception e) {
            if (dialog.isShowing())
                dialog.dismiss();
            Toast.makeText(getApplicationContext(), "Exception Message 1", Toast.LENGTH_LONG).show();
            Log.e(e.getClass().getName(), e.getMessage(), e);
            return null;
        }

2 个答案:

答案 0 :(得分:0)

使用以下方法:

Bitmap bm = ShrinkBitmap(imagefile, 300, 300);
   image.setImageBitmap(bm);

Bitmap ShrinkBitmap(String file, int width, int height) {
    BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
    bmpFactoryOptions.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
    int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) height);
    int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) width);
    if (heightRatio > 1 || widthRatio > 1) {
          if (heightRatio > widthRatio) {
              bmpFactoryOptions.inSampleSize = heightRatio;
          } else {
              bmpFactoryOptions.inSampleSize = widthRatio; 
          }
    }
    bmpFactoryOptions.inJustDecodeBounds = false;
    bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
    return bitmap;
}

或者在设置图像位图时使用inSampleSize

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
imageView.setImageBitmap(BitmapFactory.decodeFile(path, options));

答案 1 :(得分:0)

您可以将以下属性添加到高内存的最明显文件的应用程序标记。

android:largeHeap="true"