使用Base64InputStream将位图转换为Base64

时间:2015-03-02 03:18:51

标签: android bitmap base64 android-bitmap

我正在开发一款能够将Base64编码图像发送到后端的Android应用。由于某些图像很大(我因此而失去内存错误),我想使用Base64InputStream对图像进行编码。

我目前有以下内容:

import org.apache.commons.io.IOUtils;
import android.util.Base64;
import android.util.Base64InputStream;

...

public static String convertBitmapToBase64String(Context context, Bitmap bmp)
{

    try {

        ByteArrayOutputStream fos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.close();
        byte[] bmpInByteArray = fos.toByteArray();

        InputStream in = new ByteArrayInputStream(bmpInByteArray);
        final InputStream base64InputStream = new Base64InputStream(in, Base64.DEFAULT);

        //Now that we have the InputStream, we can read it and put it into the String
        final StringWriter writer = new StringWriter();
        IOUtils.copy(base64InputStream, writer, "UTF-8");

        String res = writer.toString();

        DataUtils.log("Base64 is: " + res);
        return res;

    } catch (Exception e) {

        DataUtils.log(e.getMessage());
        return "";
    }
}

然而这不起作用。我总是在IOUtils.copy(base64InputStream, writer, "UTF-8");行上收到一条例外,上面写着“bad base-64”的消息。

任何提示?

3 个答案:

答案 0 :(得分:0)

final InputStream base64InputStream = new Base64InputStream(in,Base64.DEFAULT);

我认为您应该使用final InputStream base64InputStream= = new Base64InputStream(in, Base64.DEFAULT,true);代替

因为你正在做编码工作。

public Base64InputStream(InputStream in, int flags) {
    this(in, flags, false);
}
/**
 * Performs Base64 encoding or decoding on the data read from the
 * wrapped InputStream.
 *
 * @param in the InputStream to read the source data from
 * @param flags bit flags for controlling the decoder; see the
 *        constants in {@link Base64}
 * @param encode true to encode, false to decode
 *
 * @hide
 */
public Base64InputStream(InputStream in, int flags, boolean encode) 

答案 1 :(得分:0)

尝试将位图转换为base64字符串

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
 byte[] byteArray = byteArrayOutputStream .toByteArray();
    String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);

答案 2 :(得分:0)

您必须使用Base64OutputStream,而不是Base64InputStream。

// Convert bitmap to base-64 png
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
Base64OutputStream base64FilterStream = new Base64OutputStream(byteStream, 0);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, base64FilterStream);

base64FilterStream.flush();
byteStream.flush();
base64FilterStream.close();
byteStream.close();

String base64String = byteStream.toString();