之前一直没有做过涉及到图片存储的应用,最近要做的东东涉及到了这个点,就做了一个小的例子算是对图片存储的初试吧
1.创建表:
CREATE TABLE photo (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) COMMENT ‘名称’,
photo blob COMMENT ‘照片’
)
ENGINE=InnoDB
DEFAULT CHARSET=utf8
COLLATE=utf8_general_ci;
图片在MySql中的数据存储格式为blob类型;Blob是一个可以存储二进制文件的容器。
2.编写图片流数据存取的工具类:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class ImageUtil {
private static File file = null;
/**
* 从本地文件读取图像的二进制流
*
* @param infile
* @return
*/
public static FileInputStream getImageByte(String infile) {
FileInputStream imageByte = null;
file = new File(infile);
try {
imageByte = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return imageByte;
}
/**
* 将图片流读出为图片
*
* @param inputStream
* @param path
*/
public static void readBlob(InputStream inputStream, String path) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(path);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
inputStream.close();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上就是Java+MySql图片数据保存与读取的具体实例的详细内容,更多请关注gaodaima搞代码网其它相关文章!