android - 在不创建位图的情况下获取 Drawable 的 byte[]

标签 android bitmap drawable

我需要将 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/

相关文章:

android - React Native Alert.alert() 仅适用于 iOS 和 Android,不适用于 Web

android - ImageView 使用 AccelerateDecelerateInterpolator 只旋转一次

c# - 位图到 int[] 使用 Marshal.Copy()

android - 我不希望 Android 自动调整位图的大小

android - 合并多个可绘制对象

android - 找不到资源 : Theme. Leanback

android - StorageException : An unknown error occurred, 请检查服务器响应的 HTTP 结果代码和内部异常

c# - 将位图转换为图标

android系统drawable ic_btn_round_more

android - 防止 Proguard 删除特定的可绘制对象