Search code examples
androidvarbinary

display images in android stored as varbinary in sql


i have images stored as varbinary in SQL table, how can display the images in android client

this is how image look like in the table


Solution

  • What you need to do is

    • Convert the Image string from DB to a ByteArray
    • Use BitmapFactory in android to convert from ByteArray to Bitmap
    • Set the bitmap of your imageview
      • val imageText = "FFDD8FFE000104A4694600010101000000000000FFEE1138..."
      • myImageView.setImageBitmap(getBitmap(imageText))

    You could use the following function [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)
    }