【问题标题】:What is the most efficient way to convert image to Base64 in Android?在Android中将图像转换为Base64的最有效方法是什么?
【发布时间】:2013-03-29 20:16:24
【问题描述】:

我正在寻找在 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;
}

【问题讨论】:

  • 您可以获取字节数组并将其拆分为几个子数组并在单独的线程中对其进行编码,然后将结果组合在一起以获得最终字符串。

标签: android base64 type-conversion android-image


【解决方案1】:

以下是我主要的处理方式,这是在调用图像选择器活动后的 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);

【讨论】:

  • 您正在将位图加载到内存中,这会消耗大量内存。我以前的代码和你的很像,现在把它改成了我现在在 OP 上的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-15
  • 1970-01-01
  • 2011-06-27
  • 2011-05-29
  • 2018-11-30
相关资源
最近更新 更多