Java 读取数据库Image 生成图片写入本地预览为XX
Java 读取数据库Image 生成图片写入本地预览为XX
代码:
//读取数据库Image转成byte[]
String picName=map.get(keys.get(7))==null?"1":map.get(keys.get(7)).toString()+".png";
byte[] photo=map.get(keys.get(3))==null?null:ObjectAndByte.toByteArray(map.get(keys.get(3)));
//byte[]生成图片写入本地
PicUtil.byte2image(photo, "D:\\"+picName);
/**
* byte数组到图片
* @param data
* @param path
*/
public static void byte2image(byte[] data,String path){
if(data.length<3||path.equals("")) return;
try{
FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
imageOutput.write(data, 0, data.length);
imageOutput.close();
System.out.println("Make Picture success,Please find image in " + path);
} catch(Exception ex) {
System.out.println("Exception: " + ex);
ex.printStackTrace();
}
}
/**
* 对象转数组
* @param obj
* @return
*/
public byte[] toByteArray (Object obj) {
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bytes = bos.toByteArray ();
oos.close();
bos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return bytes;
}