1

How to render an Image file (Blob) stored in the database using a custom tag, I used to render a logo but the image is being crashed and the output is the byte array.

This is what I tried:

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' />"
    }
}

The output is as follows:

enter image description here

enter image description here

How can the company?.logo be rendered as an image and not a byte array ?

2 Answers 2

6

It sounds like you want to provide a data URI, basically. For that you'll want something like:

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

where "xxx" is the data in base64 format.

So for example, using this public domain base64 library:

out << "<img src='data:img/png;base64,"
out << Base64.encode(company?.logo)
out << "' width='150' height='70' />"
Sign up to request clarification or add additional context in comments.

Comments

0

I was trying to do this same thing in Grails 3.0.11, and the Base64.encode line gave me an error. This is the resulting taglib that I came up with, which works great for me:

/** 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<< "/>"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.