如何解决的OutOfMemoryError位图在Android中? [英] How to resolve OutOfMemoryError on Bitmap in Android?

查看:201
本文介绍了如何解决的OutOfMemoryError位图在Android中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

当我使用前置摄像头,也没有问题。图片上传成功。问题是与由该装置的前摄像机拍摄的图像。什么是这个问题的解决方案?谁能帮助?

下面是code到图片的路径转换为一个字符串,并通过它传递意图

 如果(要求code == CAMERA_REQUEST&放大器;&安培;结果code == RESULT_OK){
        光标光标= getContentResolver()查询(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,新的String [] {MediaStore.Images.Media.DATA,MediaStore.Images.Media.DATE_ADDED,MediaStore.Images.ImageColumns.ORIENTATION},MediaStore.Images .Media.DATE_ADDED,NULL,DATE_ADDED ASC);
        如果(光标= NULL&放大器;!&安培; cursor.moveToFirst())
        {
            做{
              URI的uri = Uri.parse(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)));
              photoPath = uri.toString();            }而(cursor.moveToNext());
            cursor.close();            尝试{
                意向意图=新意图(MainActivity.this,ImageUploadActivity.class);
                intent.putExtra(的ImagePath,photoPath);
                MainActivity.this.startActivity(意向);
            }
            赶上(例外五)
            {
                Toast.makeText(MainActivity.this调用的方法+ photoPath,Toast.LENGTH_SHORT).show();
            }
        }

在第二个活动接收意图:

 意图camIntent = getIntent();
 camPicPath = camIntent.getExtras()的getString(的ImagePath);
 ImageView的=(ImageView的)findViewById(R.id.imgView);
 imageView.setImageBitmap(BitmapFactory.de codeFILE(camPicPath));
 Toast.makeText(getApplicationContext(),百代+ camPicPath,Toast.LENGTH_SHORT).show();
 位图=(BitmapFactory.de codeFILE(camPicPath));

方法上载文件:

 类ImageUploadTask扩展的AsyncTask<太虚,太虚,字符串> {
    @覆盖
    保护字符串doInBackground(虚空...... unsued){
        尝试{
            HttpClient的HttpClient的=新DefaultHttpClient();
            HttpContext的localContext =新BasicHttpContext();
            HttpPost httpPost =新HttpPost(http://11.10.11.15/test/upload.php);            MultipartEntity实体=新MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);            ByteArrayOutputStream BOS =新ByteArrayOutputStream();
            bitmap.com preSS(Bitmap.Com pressFormat.JPEG,100,BOS);
            字节[]数据= bos.toByteArray();
          / * entity.addPart(uploaded_file,新ByteArrayBody(数据,
                    myImage.jpg这个参数)); * /            //字符串newFilename = filename.concat(文件);
            // newFilename =文件名+ newFilename;            entity.addPart(uploaded_file,新ByteArrayBody(数据,
                    文件名));
          // Log.e(TAG调用的方法);
            httpPost.setEntity(实体);
            HTT presponse响应= httpClient.execute(httpPost,
                    localContext);
            读者的BufferedReader =新的BufferedReader(
                    新的InputStreamReader(
                            。response.getEntity()的getContent(),UTF-8));            StringBuilder的建设者=新的StringBuilder();
            字符串辅助=;            而((AUX = reader.readLine())!= NULL){
                builder.append(辅助);
            }            串sResponse = builder.toString();
            返回sResponse;
        }赶上(例外五){
            如果(dialog.isShowing())
                dialog.dismiss();
            Toast.makeText(getApplicationContext(),异常消息1,Toast.LENGTH_LONG).show();
            Log.e(e.getClass()的getName(),e.​​getMessage(),E。);
            返回null;
        }


解决方案

使用下面的方法:

 位图BM = ShrinkBitmap(镜像文件,300,300);
   image.setImageBitmap(BM);位图ShrinkBitmap(字符串的文件,诠释的宽度,高度INT){
    BitmapFactory.Options bmpFactoryOptions =新BitmapFactory.Options();
    bmpFactoryOptions.inJustDe codeBounds = TRUE;
    位图位图= BitmapFactory.de codeFILE(文件,bmpFactoryOptions);
    INT heightRatio =(int)的Math.ceil(bmpFactoryOptions.outHeight /(浮点)高度);
    INT widthRatio =(int)的Math.ceil(bmpFactoryOptions.outWidth /(浮点)宽度);
    如果(heightRatio→1 || widthRatio→1){
          如果(heightRatio> widthRatio){
              bmpFactoryOptions.inSampleSize = heightRatio;
          }其他{
              bmpFactoryOptions.inSampleSize = widthRatio;
          }
    }
    bmpFactoryOptions.inJustDe codeBounds = FALSE;
    位= BitmapFactory.de codeFILE(文件,bmpFactoryOptions);
    返回位图;
}

或使用背景图像的位图这样当 inSampleSize

  BitmapFactory.Options选项=新BitmapFactory.Options();
options.inSampleSize = 4;
imageView.setImageBitmap(BitmapFactory.de codeFILE(路径选择));

I want to set an image in ImageView, I am retrieving the image path in my first activity and I am passing it via Intent as a String to second activity. In the second activity I set the path to an ImageView. It's working properly, and I need to upload that picture to a server. So I decoded the path to a bitmap. It throws an OutOfMemoryError. How to resolve this issue?

And when I use front camera, there is no issues. Image is uploaded successfully. The problem is with the images taken by front camera of the device. What is the solution for this problem? Can anyone help?

Here is the code to convert the image path to a string and passing it via 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();
            }
        }

Receiving Intent in Second Activity:

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

Method to Upload the file:

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

解决方案

Use the following method:

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

Or use inSampleSize when setting the image bitmap like this:

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

这篇关于如何解决的OutOfMemoryError位图在Android中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆