【问题标题】:How to render a byte array (Blob) as image using TagLib如何使用 TagLib 将字节数组(Blob)呈现为图像
【发布时间】:2014-06-18 05:59:28
【问题描述】:

如何使用自定义标签渲染存储在数据库中的图像文件(Blob),我曾经渲染一个徽标,但图像正在崩溃,输出是字节数组。

这是我尝试过的:

def logo = { attrs, body ->
    if(session?.companyId && session?.companyId != 'null'){
        Company company = Company.findById(session?.companyId)
        if (!company || !company?.logo) {
            println "No response..."
            out <<"<img src='/cdc/static/images/logo.png' width='150' height='70' />"
        }
        else{
            println "Writing..."
            out << "<img src='"
            out << company?.logo
            out << "' width='150' height='70' />"
        }
    }
    else{
        println "No response..."
        //out <<"<img src='/cdc/static/images/logo.png' width='150' height='70' />"
    }
}

输出如下:

如何将company?.logo呈现为图像而不是字节数组?

【问题讨论】:

    标签: grails groovy


    【解决方案1】:

    听起来你想提供一个data URI,基本上。为此,您需要以下内容:

    src="data:img/png;base64,xxx"
    

    其中“xxx”是base64格式的数据。

    例如,使用this public domain base64 library:

    out << "<img src='data:img/png;base64,"
    out << Base64.encode(company?.logo)
    out << "' width='150' height='70' />"
    

    【讨论】:

      【解决方案2】:

      我试图在 Grails 3.0.11 中做同样的事情,而 Base64.encode 行给了我一个错误。这是我想出的结果标签库,对我来说非常有用:

      /** imgFromByteArray
       *
       * Print a byte array as an image tag.
       *
       * attrs:
       *      1. String imageType         Example: image/jpeg
       *      2. byte[] imageContent
       *      #. Any additional attrs will be included in the <img /> tag
       */
      def imgFromByteArray = { attrs ->
      
          //Get image content and type from attrs
          byte[] imageContent = attrs.imageBytes
          String imageType = attrs.imageType
      
          //Remove attributes that should not be printed in the img tag
          ['imageBytes', 'imageType'].each{
              if(attrs.containsKey(it)){ attrs.remove(it) }
          }
      
          //Print the image tag with image content
          out << """<img src='data:${imageType};base64,${imageContent?.encodeBase64()}'"""
      
          //Include any other tags given
          attrs.each { attrLabel, attrValue ->
              out << " ${attrLabel}=\"${attrValue}\""
          }
      
          //Close the image tag
          out<< "/>"
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-06
        • 2018-08-01
        • 1970-01-01
        • 2012-06-07
        • 1970-01-01
        • 2011-04-17
        相关资源
        最近更新 更多