在Android中将图像转换为Base64的最有效方法是什么?

时间:2013-04-07 20:25:10

标签: android base64 type-conversion android-image

我正在寻找在Android中将图像文件转换为Base64字符串的最有效方法。

图像必须一次发送到一个Base64字符串中,然后发送到后端。

首先我使用imageToByteArray然后使用imageToBase64来获取String。

    public static byte[] imageToByteArray(String ImageName) throws IOException {
    File file = new File(sdcard, ImageName);
    InputStream is = new FileInputStream(file);

    // Get the size of the file
    long length = file.length();

    // Create the byte array to hold the data
    byte[] bytes = new byte[(int)length];

    // Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
           && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
        offset += numRead;
    }

    //Close input stream
    is.close();
    // Ensure all the bytes have been read in
    if (offset < bytes.length) {
        throw new IOException("Could not completely read file "+file.getName());
    }
    return bytes;
}

    public String imageToBase64(String ImageName){      
    String encodedImage = null;
    try {
        encodedImage = Base64.encodeToString(imageToByteArray(ImageName), Base64.DEFAULT);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return encodedImage;
}

1 个答案:

答案 0 :(得分:0)

下面是我如何处理它,这是在调用图像选择器活动后的gotActivityResults回调中。它与你的类似,但我认为它会更高效,因为来自流的toByteArray是它背后的本机c代码,而不是你自己的java循环。

                       Uri selectedImage = imageReturnedIntent.getData();
                       InputStream imageStream = getContentResolver().openInputStream(selectedImage);
                       Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
                       ByteArrayOutputStream bao = new ByteArrayOutputStream();

                       yourSelectedImage.compress(Bitmap.CompressFormat.JPEG, 90, bao);

                       byte [] ba = bao.toByteArray();

                       String ba1= Base64.encodeToString(ba, 0);

                       HashMap<String, String > params = new HashMap<String, String>();
                       params.put("avatar", ba1);
                       params.put("id", String.valueOf(uc.user_id));
                       params.put("user_id", String .valueOf(uc.user_id));
                       params.put("login_token", uc.auth_token);
                       uc.setAvatar(params);