位图OutOfMemoryException?

时间:2015-06-01 12:26:21

标签: android

在将位图图像发送到服务器之前,我将其压缩。上传图片操作总是成功的。但是在一段时间后应用程序崩溃

例外:

java.lang.OutOfMemoryError: Failed to allocate a 230412 byte allocation with 168272 free bytes and 164KB until OOM

代码:

        HttpPost httpPost = new HttpPost(url);
        HttpClient httpClient = new DefaultHttpClient();
        MultipartEntity reqEntity = new MultipartEntity();
        Charset charsUTF8 = Charset.forName("UTF-8"); 
        HttpResponse httpResponse;

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        BitmapUtils.getBitmap(context,url).compress(CompressFormat.JPEG, 10, stream);
        byte[] byteArray = stream.toByteArray();
        ByteArrayBody body = new ByteArrayBody(byteArray, name + ".jpg");

        reqEntity.addPart("photo", body);

        httpPost.setEntity(reqEntity);
        httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        String stringData = EntityUtils.toString(httpEntity);

BitmapUtils类:

    private static Uri getImageUri(String path) {
        return Uri.fromFile(new File(path));
    }
    public static Bitmap getBitmap(Context context,String path) {
        Uri uri = getImageUri(path);
        InputStream in = null;
        try {
            in = context.getContentResolver().openInputStream(uri);

            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;

            BitmapFactory.decodeStream(in, null, o);
            in.close();

            int scale = 1;
            if (o.outHeight > 1024 || o.outWidth > 1024) {
                scale = (int) Math.pow(2, (int) Math.round(Math.log(1024 / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
            }

            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            in = context.getContentResolver().openInputStream(uri);
            Bitmap b = BitmapFactory.decodeStream(in, null, o2);
            in.close();

            return b;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

请问您能解释一下有什么问题吗?如何检测java.lang.OutOfMemoryError异常。

0 个答案:

没有答案