Java 如何从SD卡上拍摄图像?以及如何转换为字符串(base64)
我需要从sd卡访问图像。我有他们的路。我怎样才能把它们转换成以64为基数的字符串呢?这样做。。。然后,您可以根据需要读取该文件Java 如何从SD卡上拍摄图像?以及如何转换为字符串(base64),java,android,image,base64,sd-card,Java,Android,Image,Base64,Sd Card,我需要从sd卡访问图像。我有他们的路。我怎样才能把它们转换成以64为基数的字符串呢?这样做。。。然后,您可以根据需要读取该文件 File dir = Environment.getExternalStorageDirectory(); File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext"); 试试这个。您可以使用以下代码 File dir = Environment.getExternalStorageDi
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
试试这个。您可以使用以下代码
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;
}
File dir=Environment.getExternalStorageDirectory();
File yourFile=新文件(dir,“path/to/the/File/inside/the/sdcard.ext”);
字符串encodeFileToBase64Binary=encodeFileToBase64Binary(您的文件);
私有静态字符串encodeFileToBase64Binary(文件名)引发IOException{
字节[]字节=加载文件(文件名);
byte[]encoded=Base64.encodeBase64(字节);
字符串编码字符串=新字符串(已编码);
返回编码环;
}
私有静态字节[]加载文件(文件文件)引发IOException{
InputStream is=新文件InputStream(文件);
long length=file.length();
if(长度>整数最大值){
//文件太大
}
字节[]字节=新字节[(int)长度];
整数偏移=0;
int numRead=0;
而(偏移量=0){
偏移量+=numRead;
}
if(偏移量<字节长度){
抛出新IOException(“无法完全读取文件”+file.getName());
}
is.close();
返回字节;
}