2011-09-13 60 views
2

我想获得一个JPEG图像的字节数组,而不使用下面的方法:获取JPEG图像的字节数组,而不会压缩

bitmap = BitmapFactory.decodeFile("/sdcard/photo.jpg"); 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    bitmap.compress(CompressFormat.JPEG, 50, baos); 
    byte[] data = baos.toByteArray(); 

反正有没有做到这一点?

回答

3

任何理由不只是加载文件本身作为一个正常的FileInputStream等? (我个人喜欢番石榴的Files.toByteArray()作为加载文件的简单方式,但我不知道Android上的番石榴的状态。)

+0

我可以知道我怎么做到这一点? – androidnoob

+3

@androidnoob:你知道如何从文件中读取吗?我强烈建议在尝试进一步深入之前阅读关于核心Java(集合,流等)的书,说实话。我并不想粗鲁,但在尝试认真对待任何问题之前,掌握平台的基础知识非常重要,像StackOverflow这样的问答网站并不是获得这些知识的最佳途径。 –

+0

@androidnoob,为了将文件读入字节数组,我(也)认为您最好使用像[Guava]这样的库中的实用程序方法(http://code.google.com/p/guava-libraries/ )或[Commons IO](http://commons.apache.org/io/)。 (如果整个库太大,你可以参加相关课程。) [这个问题](http://stackoverflow.com/questions/6058003/beautiful-way-to-read-file-into-byte-array-in-java)的一些例子。 – Jonik

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; 
} 
+2

一个空的catch块,捕获所有异常?伊克。 –

+0

:)这只是一个复制代码片段。 – NyanLH

+2

所以你*邀请*某人显然不知道如何使用流来复制后面的代码*非常不好的练习*(哦,我刚刚注意到你没有关闭异常文件),没有包括*任何*种警告呢?双喜。 –