我正在将jpg图像存储在数据库中(作为字节数组)。我想避免在网页上显示之前落入文件系统。
单元测试表明,数据库存储和检索工作正常,没有损坏。可以从数据库中提取Fies并转换回jpg文件
图像被转换为byte数组并使用以下代码存储在数据库中:
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,其中包含从数据库中检索的字节数组。这个类还有一个将byte数组转换为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-....
任何提示都将不胜感激
好吧,事实证明这非常容易,我在问这个问题的两分钟内就解决了,但我打赌其他人也会有同样的问题。
答案是不要使用URLSafe
它适用于编码Base64String()