问题
I am storing jpg images in a database (as byte array). I want to avoid dropping onto filesystem before showing on a web page.
Unit Tests show that database storage and retrieval are working without corruption. Fies can be extracted from database and converted back to jpg file
The image was converted to bytearray and stored in database with the following code:
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;
}
I have a class ViewWrapperMediaImage that contains the byte array retrieved from the database. This class also has a method that converts the bytearray to 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;
}
}
My Thymeleaf tile then calls the conversion method generateBase64Image():
<img th:src="@{'data:image/jpeg;base64,'+${vwNewTestContentElement.generateBase64Image()}}" />
It doesn't work.
The generated html source is as follows:
< img src="data:image/jpeg;base64,_9j_4AAQSkZJRgABAgAAAQABAAD_2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL_2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL_wAARCADhASwDASIAAhEBAxEB_8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL_8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4-Tl5ufo6erx8vP09fb3-....
Any hints would be deeply appreciated
回答1:
OK, it turns out this is dead easy, I solved within 2 mins of asking the question, but I bet others will have the same question.
The answer is don't use URLSafe
It works with encodeBase64String()
来源:https://stackoverflow.com/questions/33045743/showing-base64string-image-with-thymeleaf