我将 jpg 图像存储在数据库中(作为字节数组)。我想避免在网页上显示之前放入文件系统。
单元测试表明数据库存储和检索工作正常,没有损坏。Fies可以从数据库中提取并转换回jpg文件
图像被转换为字节数组并使用以下代码存储在数据库中:
public static byte[] getImageAsBytes(BufferedImage buffer) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(buffer, "jpg", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
return imageInByte;
}
我有一个 ViewWrapperMediaImage 类,其中包含从数据库中检索到的字节数组。此类还有一个将 bytearray 转换为 base64 String 的方法。
package jake.prototype2.controller.viewwrapper;
import org.apache.commons.codec.binary.Base64;
import jake.prototype2.model.assessment.MediaImage;
import jake.prototype2.model.assessment.TestStructureException;
import jake.prototype2.model.structure.InterfacePersistenceBean;
public class ViewWrapperMediaImageCreate extends ViewWrapperTestContentElementCreate
{
private byte[] image;
protected String mediaFileName;
private static final long serialVersionUID = 4181515305837289526L;
public ViewWrapperMediaImageCreate(InterfacePersistenceBean persistenceBean) throws TestStructureException
{
....
}
}
public byte[] getImage()
{
return image;
}
public String generateBase64Image()
{
return Base64.encodeBase64URLSafeString(this.getImage());
}
public void setImage(byte[] image)
{
this.image = image;
}
public String getMediaFileName()
{
return mediaFileName;
}
public void setMediaFileName(String mediaFileName)
{
this.mediaFileName = mediaFileName;
}
}
然后我的 Thymeleaf 瓦片调用转换方法 generateBase64Image():
<img th:src="@{'data:image/jpeg;base64,'+${vwNewTestContentElement.generateBase64Image()}}" />
它不起作用。
生成的html源码如下:
< img src="data:image/jpeg;base64,_9j_4AAQSkZJRgABAgAAAQABAAD_2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL_2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL_wAARCADhASwDASIAAhEBAxEB_8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL_8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4-Tl5ufo6erx8vP09fb3-....
任何提示将不胜感激