Android - 如何加载大图像(将其转换为较小的尺寸)并将其作为 Base64 字节数组发送(避免 OutOfMemory 错误)

标签 android image bitmap out-of-memory arrays

我想在我的应用程序中将照片图像发送到服务器。 API使用Base64格式的图像。我有图像/照片的路径,现在我想将此路径转换为 ​​Base64 数组。

为了加载图像,我有以下代码(它还将图像大小调整为最大尺寸):here :

private Bitmap getBitmap(String path) {

Uri uri = getImageUri(path);
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = mContentResolver.openInputStream(uri);

// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();



int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) > 
      IMAGE_MAX_SIZE) {
   scale++;
}
Log.d(TAG, "scale = " + scale + ", orig-width: " + o.outWidth + ", 
   orig-height: " + o.outHeight);

Bitmap b = null;
in = mContentResolver.openInputStream(uri);
if (scale > 1) {
    scale--;
    // scale to max possible inSampleSize that still yields an image
    // larger than target
    o = new BitmapFactory.Options();
    o.inSampleSize = scale;
    b = BitmapFactory.decodeStream(in, null, o);

    // resize to desired dimensions
    int height = b.getHeight();
    int width = b.getWidth();
    Log.d(TAG, "1th scale operation dimenions - width: " + width + ",
       height: " + height);

    double y = Math.sqrt(IMAGE_MAX_SIZE
            / (((double) width) / height));
    double x = (y / height) * width;

    Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x, 
       (int) y, true);
    b.recycle();
    b = scaledBitmap;

    System.gc();
} else {
    b = BitmapFactory.decodeStream(in);
}
in.close();

Log.d(TAG, "bitmap size - width: " +b.getWidth() + ", height: " + 
   b.getHeight());
return b;
} catch (IOException e) {
 Log.e(TAG, e.getMessage(),e);
 return null;
}

这是发送图像的代码:

        image = getBitmap(pathToImage);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        String filenameArray[] = fileName.split("\\.");
        String extension = filenameArray[filenameArray.length - 1];

        if (extension.equalsIgnoreCase("jpg")
                || extension.equalsIgnoreCase("jpeg"))
            image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        else
            image.compress(Bitmap.CompressFormat.PNG, 100, stream);

        image.recycle();
        image = null;

        byte[] byteArray = stream.toByteArray();

        try {
            stream.close();
        } catch (IOException e1) {

        }

        stream = null;

        ByteArrayOutputStream baos = new ByteArrayOutputStream(
                (int) (byteArray.length * 1.5));

        JsonGenerator jgenerator = null;

        try {
            jgenerator = new JsonFactory().createGenerator(baos);

            jgenerator.writeStartObject();
            jgenerator.writeStringField("fileName", fileName);
            // Jackson takes care of the base64 encoding for us
            jgenerator.writeBinaryField("content", byteArray);
            jgenerator.writeEndObject();
            jgenerator.close();

        } catch (JsonGenerationException e) {
        } catch (IOException e) {
        }

        HttpClient httpClient = new DefaultHttpClient();

        HttpPost httppost = new HttpPost(Globals.URL + "/storageUploadFile");

        httppost.setHeader("Token", Globals.Token);
        httppost.setHeader("Content-type",
                "application/json; charset=utf-8");

        httppost.setEntity(new ByteArrayEntity(baos.toByteArray()));

        HttpResponse response;
        try {
            response = httpClient.execute(httppost);

            HttpEntity httpentity = response.getEntity();

            msg = EntityUtils.toString(httpentity);

            jgenerator = null;
            httppost = null;
            httpClient = null;
            httpentity = null;

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

有时我会在行 BitmapscaledBitmap = Bitmap.createScaledBitmap(b, (int) x, (int) y, true); 或行 jgenerator.writeBinaryField( “内容”,byteArray);

你能帮我修改代码以避免 OutOfMemory 错误吗?您是否有一些如何将图像从文件转换为 Base64 并将其作为 HTTPPost 发送的提示?

最佳答案

您尝试过Picasso吗?图书馆?

AsyncTask<String,Void,Void> downloadAndResizePictureTask = new AsyncTask<String,Void,Void>(){
    @Override 
    public Void doInBackground(String... params){
       //assuming params[0] is a valid url
       Bitmap bmp = Picasso.with(getActivity()).load(params[0]).resize(150,150).get();
       ByteArrayOutputStream stream = new ByteArrayOutputStream();
       bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
       byte[] byteArray = stream.toByteArray();
       //do what needs to be done to convert to Base64

    }
}

关于Android - 如何加载大图像(将其转换为较小的尺寸)并将其作为 Base64 字节数组发送(避免 OutOfMemory 错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25265944/

相关文章:

android - 在 Android 中按下电源按钮时播放声音

Android 工具栏覆盖了一个 fragment

c++ - QWebView获取图片的方法

ruby-on-rails - Rails + Dragonfly gem : Saving image in a directory structure based on ActiveRecord object attributes

python - 在Python中重新排列图像

android调整大小动画

wpf - 从 WPF 中的图像获取绝对文件路径

android - 在 View.getDrawingCache() 中获取空指针异常

java - 如何以编程方式在中心裁剪特定尺寸的位图

android - 从现有源创建 android 项目后缺少 R 类