如何使用自定义标记渲染存储在数据库中的图像文件(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' />"
}
}
输出如下:
如何将公司?.logo 呈现为图片而不是字节数组?
答案 0 :(得分:6)
听起来你想提供一个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' />"
答案 1 :(得分:0)
我试图在Grails 3.0.11中做同样的事情,而Base64.encode行给了我一个错误。这是我想出的结果taglib,对我来说很有用:
/** 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<< "/>"
}