【问题标题】:Get byte[] of a Drawable without Bitmap creation在不创建位图的情况下获取 Drawable 的字节 []
【发布时间】:2013-01-25 20:47:59
【问题描述】:

我需要将 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 访问,但我不知道如何获得正确的路径。

有什么想法吗?

【问题讨论】:

  • 我在Resources.openRawResource(R.drawable.*) 上做了一些测试,但没有得到稳定的结果。这意味着InputStream 的长度与我在文件系统上看到的不匹配。无论如何,这可能会给您提供将Drawable 直接读取为InputStream 并将其转发给您的OutputStream 的方法。

标签: android bitmap drawable


【解决方案1】:

harism 给了我最后的提示:使用Resoureces.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 毫秒。

希望有人可以使用这个解决方案。

【讨论】:

    猜你喜欢
    • 2012-06-25
    • 2012-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    相关资源
    最近更新 更多