开发者

Obtain byte array of a JPEG image without compressing

开发者 https://www.devze.com 2023-04-05 00:02 出处:网络
I would like to obtain the byte array of a JPEG image witho开发者_StackOverflow社区ut using the following method:

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消