I would like to obtain the byte array of a JPEG image witho开发者_StackOverflow社区ut using the following method:
bitmap = BitmapFactory.decodeFile("/sdcard/photo.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 50, baos);
byte[] data = baos.toByteArray();
Is there anyway to do this?
Any reason not to just load the file itself as a normal FileInputStream
etc? (Personally I like Guava's Files.toByteArray()
as a simple way of loading a file, but I don't know the status of Guava on Android.)
If you consider it as a normal file type, then it would solve your problem.
here is the code
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;
}
精彩评论