首页 > 解决方案 > 在 sql 中显示存储为 varbinary 的 android 中的图像

问题描述

我在 SQL 表中存储为 varbinary 的图像,如何在 android 客户端中显示图像

这就是图像在表格中的样子

标签: androidvarbinary

解决方案


你需要做的是

  • Image字符串从 DB 转换为ByteArray
  • 在android中使用BitmapFactory转换ByteArrayBitmap
  • 设置图像视图的位图
    • val imageText = "FFDD8FFE000104A4694600010101000000000000FFEE1138..."
    • myImageView.setImageBitmap(getBitmap(imageText))

您可以使用以下功能 [kotlin]

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.google.android.gms.common.util.Hex

/**
 * Converts a hex string to Bitmap
 *
 * @param image  hex string e.g. "FFD8FFE0..."
 * @return Bitmap
 */
fun getBitmap(image: String): Bitmap {
    // Convert String to ByteArray
    val byteArray = Hex.stringToBytes(image)
    // Convert ByteArray Bitmap
    return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
}

推荐阅读