我需要将 PNG 发送到服务器。一个非常简单的解决方案是创建一个 Bitmap
并使用以下代码将其转换为 byte[]
:
final Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.some_image);
final ByteArrayOutputStream os = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 100, os);
final byte[] data = os.toByteArray();
因为我想节省时间和内存,所以我想在不需要创建位图的情况下实现这一点。
一个想法是将 Drawable
作为 File
访问,但我不知道如何获得正确的路径。
有什么想法吗?
最佳答案
harism 给了我最后的提示:使用 Resourceces.openRawResource
方法之一。
这是我的最终解决方案:
private byte[] fetchImageData(Resources res) throws IOException {
final AssetFileDescriptor raw = res.openRawResourceFd(R.drawable.some_image);
final FileInputStream is = raw.createInputStream();
// there are plenty of libraries around to achieve this with just one line...
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
final byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
return buffer.toByteArray();
}
在我的例子中,我有一个 250x200 像素的 PNG 和一个 42046 字节的文件大小。 Bitmap
方法需要大约 500 毫秒,原始方法需要 3 毫秒。
希望有人可以使用这个解决方案。
关于android - 在不创建位图的情况下获取 Drawable 的 byte[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14530128/