我想使用以下方法获取JPEG图像不带的字节数组:
bitmap = BitmapFactory.decodeFile("/sdcard/photo.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 50, baos);
byte[] data = baos.toByteArray();
有没有这样做?
答案 0 :(得分:3)
有什么理由不将文件本身加载为普通FileInputStream
等? (我个人喜欢Guava的Files.toByteArray()
作为加载文件的简单方法,但我不知道Android上Guava的状态。)
答案 1 :(得分:1)
如果您将其视为普通文件类型,则可以解决您的问题。
这是代码
File file = new File("/sdcard/download/The-Rock2.jpg");
byte[] bytes = getBytesFromFile(file);
public byte[] getBytesFromFile(File file) {
byte[] bytes = null;
try {
InputStream is = new FileInputStream(file);
long length = file.length();
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();
} catch (IOException e) {
//TODO Write your catch method here
}
return bytes;
}