如何解决内存不足错误的位图在Android中? [英] How to resolve Out of Memory Error on Bitmap in Android?

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

问题描述

我想在图像视图设置的图像,我取回我的第一个活动图像路径,我通过故意将它作为一个字符串,以第二activity.In第二个活动我设置路径的图像视图,它工作正常,我需要的图片上传到服务器,所以我去codeD的路径bitmap.It抛出内存不足的error.How来解决这个问题呢?。而当我使用前置摄像头,没有issues..Image会上传successfully.Problem是与所采取的device.What前方相机的图像是此problem.Can任何人的溶液帮助??

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,空,DATE_ADDED ASC);
        如果(光标= NULL和放大器;!&安培; cursor.moveToFirst())
        {
            做 {
              开放的我们的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();
            }
        }
 

在第二个活动Reciving意图

 意图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);
            byte []的数据= 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(AUX);
            }

            串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 image view,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 image view,It is working properly , and I need to upload that picture to a server,So I decoded the path to a bitmap.It throws an Out of memory error.How to resolve this issue?.And when I use front camera ,there is no issues..Image will upload successfully.Problem is with the images taken by front camera of the device.What is the solution for this problem.Can anyone Help??

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

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

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

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