简体   繁体   中英

how to write image data to a text file as a base 64 string?

im trying to write image data to a text file as a base 64 string its working if it doesnt contain to much information but when it contains quite a bit of information it crashes the application saying that its out off memory below is my code:

package com.search.visual;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;

public class SavePhotoTask extends AsyncTask<byte[], String, String>{
    String name;
    byte[] num;
    @Override
    protected String doInBackground(byte[]... params) {
        // TODO Auto-generated method stub
    File photo = new File(Environment.getExternalStorageDirectory(),".vis/image.xml");

    name = Base64.encodeToString(params[0], 0);



    //return base64String;
    if (photo.exists()){
        photo.delete();
    }
    try{



        FileWriter fi = new FileWriter(photo.getPath());
        fi.write("<Image>\n\t<Data>");
        fi.write(name);

        fi.write("</Data>\n</Image>");
        fi.close();


    }catch (IOException e) {
        // TODO: handle exception
        Log.e("pictureDemo","exception", e);
    }


    return (null);
}

    }

am i doing something wrong or is there a better way to do this?

thank you in advance

Sounds like you're simply running out of RAM. One reason this is happening is because you're holding the entire original image and the entire base-64 encoded image in memory, all at once, even if only briefly. Try writing the data out a chunk at a time in a for loop, using the variation:

encodeToString(byte[] input, int offset, int len, int flags)

And encoding and writing a few thousand bytes at a time

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM