如何从SD卡拍摄图像?以及如何转换为String(base64)

时间:2013-06-06 18:24:53

标签: java android image base64 sd-card

我需要从SD卡访问图像。我有自己的道路。我怎么能把它们转换成String base 64?

2 个答案:

答案 0 :(得分:0)

执行类似的操作......然后,您可以根据需要阅读该文件。

File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");

试试这个。

答案 1 :(得分:0)

您可以使用以下代码。

File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
String encodeFileToBase64Binary = encodeFileToBase64Binary(yourFile);

private static String encodeFileToBase64Binary(File fileName) throws IOException {
    byte[] bytes = loadFile(fileName);
    byte[] encoded = Base64.encodeBase64(bytes);
    String encodedString = new String(encoded);
    return encodedString;
}

private static byte[] loadFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);

    long length = file.length();
    if (length > Integer.MAX_VALUE) {
        // File is too large
    }
    byte[] bytes = new byte[(int) length];
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
        offset += numRead;
    }

    if (offset < bytes.length) {
        throw new IOException("Could not completely read file " + file.getName());
    }

    is.close();
    return bytes;
}