首先,我想说我知道图像应该作为BLOB存储在数据库中......
我正在使用一个系统,其中图像已作为CLOB存储在数据库中。我只需要处理我得到的东西...因此,我向SO提出问题。
这是我到目前为止所做的...
查询数据库(使用Hibernate(,我可以成功获取单个记录及其所有字段。我正在将 CLOB 列读取到字符数组中:
@Column(name="POD_SIGNATURE_IMG", nullable=true)
@Lob
@Basic(fetch=FetchType.LAZY)
private char[] podSignatureImage;
接下来,我假设为了将图像存储在 CLOB 中,它必须经过 Base64 编码。因此,我将字符数组转换为字符串:
String base64DataString = new String(podSignatureImage);
这意味着我应该能够在我的 jsp 中执行以下操作:
<img alt="image" src="data:image/jpg;base64,${model.base64DataString}">
除了这没有奏效。我没有收到任何错误。我可以看到我的 jsp 页面,但我看不到图像。
我将不胜感激一些建议。
谢谢。
请尝试将以下内容编码为base64:
byte[] encodeBase64 = new String(podSignatureImage).getBytes();
String base64DataString = org.apache.commons.codec.binary.Base64.encodeBase64(encodeBase64);
base64DataString = new String(encodeBase64, "UTF-8");
我希望它能帮助你
你能提供一个CLOB字符串吗?
有一个函数将base64Str转换为文件。
public static void bytes2File(byte[] bytes, String filePath) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
file = new File(filePath);
BuildFileUtil.buildFile(file);
file = new File(filePath);
BuildFileUtil.buildFile(file);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
bos.flush();
System.out.println("生成完成");
} catch (Exception e) {
e.printStackTrace();
logger.error("错误:"+e);
} finally {
IOUtils.closeQuietly(bos,fos);
}
}
您可以尝试这样做进行测试。
package com.hisen.image;
import com.hisen.utils.Base64Util;
import com.hisen.utils.File2ByteArraysUtil;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import sun.misc.BASE64Encoder;
/**
* <img src="data:image/png;base64,<%=imageStr%>" alt="base64image"/>
* Created by hisenyuan on 2017/5/11 at 18:44.
*/
public class ShowImageByBase64 {
public static String showimage() {
//写相对路径会报错,暂时不知道如何解决
String imagePath = "C:\1\830.jpg";
byte[] bytes = File2ByteArraysUtil.file2Bytes(imagePath);
String s = Base64Util.encodeBase64(bytes);
return s;
}
/**
* sun.misc.BASE64Encoder
*/
public static String encodeBase64(byte[] str) {
if (str == null) {
return null;
} else {
BASE64Encoder encoder = new BASE64Encoder();
try {
return encoder.encode(str);
} catch (Exception var3) {
return null;
}
}
}
/***
* file2byte[]
* @param path
* @return
*/
public static byte[] file2Bytes(String path) {
byte[] buffer = null;
File file = new File(path);
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
}