3

我必须使用多部分实体将四个图像从 android 上传到服务器。我通过使用 base64 解码来发送图像。它显示内存不足异常。我在下面发布了代码。请帮我修复错误。

private String resize(String path) {

    ByteArrayOutputStream bAOS;
    bitmap = BitmapFactory.decodeFile(path);
    Log.i("RESIZE", "RESIZE");
    // Toast.makeText(getApplicationContext(), "resizing first image",
    // Toast.LENGTH_LONG).show();
    String encodedImage;
    byte[] imageBytes;

    try {
        Log.d("ActivityNewsDisplay", "inside try one");
        bAOS = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bAOS);
        imageBytes = bAOS.toByteArray();
        encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);

        return encodedImage;
    } catch (Exception e) {
        Log.d("ActivityNewsDisplay", "inside catch one");
        // TODO: handle exception
        return null;
    } catch (OutOfMemoryError e) {
        try {
            Log.d("ActivityNewsDisplay", "inside catch one");
            Log.d("ActivityNewsDisplay", "inside try two");
            bAOS = new ByteArrayOutputStream();

            bitmap.compress(Bitmap.CompressFormat.JPEG, 25, bAOS);
            imageBytes = bAOS.toByteArray();
            encodedImage = Base64
                    .encodeToString(imageBytes, Base64.DEFAULT);

            return encodedImage;

        } catch (OutOfMemoryError e1) {
            Log.d("ActivityNewsDisplay", "inside catch two");
            try {
                Log.d("ActivityNewsDisplay", "inside try three");
                bAOS = new ByteArrayOutputStream();
                Toast.makeText(getApplicationContext(), "resize one",
                        Toast.LENGTH_LONG).show();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 10, bAOS);
                imageBytes = bAOS.toByteArray();
                encodedImage = Base64.encodeToString(imageBytes,
                        Base64.DEFAULT);

                return encodedImage; // TODO: handle exception

            } catch (Exception e2) {
                Log.d("ActivityNewsDisplay", "inside catch three");

                return null;
            }
        }
    }

}

我在异步任务中调用此函数。

        @Override
    protected String doInBackground(String... params) {
        Log.i("inside asynchronous task", "inside task");
        // TODO Auto-generated method stub
        decodedImage = new String[params.length];
        for (int i = 0; i < params.length; i++) {
            decodedImage[i] = resize(params[i]);
        }
        publishProgress("progress");
        return null;
    }

图像尺寸大时出现内存不足异常?

4

0 回答 0