2

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

图像必须一次以单个 Base64 字符串发送到后端。

首先我使用 imageToByteArray 然后 imageToBase64 来获取字符串。

    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;
}
4

1 回答 1

0

Below is how I handle it mostly, this is in the gotActivityResults callback after calling the image picker activity. It's similar to your's but I think it will be more efficient because the toByteArray from the stream is native c code behind it as opposed to the java loop in yours.

                       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);
于 2013-04-07T23:45:25.320 回答