java实现将图片和缩略图存储到数据库中
- 格式:pdf
- 大小:93.87 KB
- 文档页数:3
jsp上传图片生成缩略图并将数据信息添加到数据库jsp上传图片生成缩略图并将数据信息添加到数据库2011-03-31 15:30转载自 sleinet最终编辑 sleinet上传页面:<form action="uppicsuolue.jsp" method="post" enctype="multipart/form-data" name="anliForm" id="anliForm"> <input type="hidden" name="comId" value="<%=comid%>"><table width="100%" border="0"><tr><td>发布者:</td><td><input name="comName" type="text" id="comName" readonly="readonly" value="<%=comName%>"/></td> </tr><tr><td>标题:</td><td><input name="anliTitle" type="text" id="anliTitle" /></td></tr><tr><td>作品类别:</td><td><select name="anliProType" id="anliProType"><SelectBean:SelectBean idNum="0" tName="list_itemproducttype"></SelectBean:SelectBean> </select></td></tr><tr><td>作品图片:</td><td><input name="file" type="file" size="30" /></td></tr><tr><td>内容</td><td><textarea name="anliContent" cols="60" rows="10"></textarea></td></tr><tr><td> </td><td><input type="submit" name="Submit" value="发布" /></td></tr></table></form>处理页面:<%@ page contentType="text/html;charset=gb2312" language="java"import="java.io.*,java.awt.Image,java.awt.image.*,com.sun.imag e.codec.jpeg.*,java.sql.*,com.jspsmart.upload.*,java.util.*,com.slei.util.*,com bean.*"%><%SmartUpload mySmartUpload =new SmartUpload();long file_size_max=1000000;String fileName2="",ext="",testvar="";String url="com/anlipic/"; //应保证在根目录中有此目录的存在mySmartUpload.initialize(pageContext); //初始化try {mySmartUpload.setAllowedFilesList("jpg,gif"); //只允许上载此类文件mySmartUpload.upload(); //上载文件} catch (Exception e){%><SCRIPT language=javascript>alert("只允许上传.jpg和.gif类型图片文件");window.location='item_anli.jsp';</script><%}try{com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);if (myFile.isMissing()){%><SCRIPT language=javascript>alert("请先选择要上传的文件");window.location='asdf.jsp';</script><%}else{//StringmyFileName=myFile.getFileName(); //取得上载的文件的文件名ext= myFile.getFileExt(); //取得后缀名int file_size=myFile.getSize(); //取得文件的大小String saveurl="";if(file_size<file_size_max){Calendar calendar = Calendar.getInstance();String filename = String.valueOf(calendar.getTimeInMillis()); //更改文件名,取得当前上传时间的毫秒数值saveurl=request.getRealPath("/")+url;saveurl+=filename+"."+ext; //保存路径System.out.println(saveurl);myFile.saveAs(saveurl,mySmartUpload.SAVE_PHYSICAL);//************************************************************* ****上传完成,开始生成缩略图java.io.File file = new java.io.File(saveurl); //读入刚才上传的文件Stringnewurl=request.getRealPath("/")+url+filename+"_min."+ext; //新的缩略图保存地址Image src = javax.imageio.ImageIO.read(file); //构造Image对象float tagsize=200;int old_w=src.getWidth(null); //得到源图宽int old_h=src.getHeight(null);int new_w=0;int new_h=0; //得到源图长int tempsize;float tempdouble;if(old_w>old_h){tempdouble=old_w/tagsize;}else{tempdouble=old_h/tagsize;}new_w=Math.round(old_w/tempdouble);new_h=Math.round(old_h/tempdouble); //计算新图长宽BufferedImage tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);tag.getGraphics().drawImage(src,0,0,new_w,new_h,null);//绘制缩小后的图FileOutputStream newimage=new FileOutputStream(newurl); //输出到文件流JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);encoder.encode(tag); //近JPEG编码newimage.close();//************************************************************* ******数据插入数据库Format format=new Format();ComBean cbean=new ComBean();String pic1=url+filename+ext;String pic2=url+filename+"_min."+ext;StringanliProType=mySmartUpload.getRequest().getParameter("anliPr oType");StringanliTitle=mySmartUpload.getRequest().getParameter("anliTitle");StringcomId=mySmartUpload.getRequest().getParameter("comId");StringcomName=mySmartUpload.getRequest().getParameter("comNa me");StringanliContent=mySmartUpload.getRequest().getParameter("anliC ontent");StringanliId=comId+String.valueOf(calendar.getTimeInMillis());String insertSql="insert into item_anli(anliId,comId,comName,anliTitle,anliProType,pic1,pic2,a nliContent,upTimes)values('"+anliId+"','"+comId+"','"+comNam e+"','"+anliTitle+"','"+anliProType+"','"+pic1+"','"+pic2+"','"+an liContent+"','"+format.getDateTime()+"')";boolean isInsert=cbean.updateslei(insertSql);if(isInsert){out.print("<SCRIPT language='javascript'>");out.print("alert('发布成功!');");out.print("window.location='item_anlictrl.jsp;'");out.print("</SCRIPT>");}else{out.print("<SCRIPT language='javascript'>");out.print("alert('系统遇忙,请稍后重试!');");out.print("window.location='item_anli.jsp;'");out.print("</SCRIPT>");}}else{out.print("<SCRIPT language='javascript'>");out.print("alert('上传文件大小不能超过"+(file_size_max/1000)+"K');");out.print("window.location='item_anli.jsp;'");out.print("</SCRIPT>");}}}catch (Exception e){e.toString();}%>。
LISTVIEW显示JPEG缩略图李海彬许多的JPEG图片浏览器(如由我设计的《JPEG浏览缩放器》),都可以将JPEG缩略图放置到Listview控件中,实现图片的预览。
要在Listview上显示图片,Listview控件必须与Imagelist控件关联,先将图片装入到IMAGELIST控件中,再通过这种方式以应:Listview1.Item[0].ImageIndex=3但是Imagelist控件仅支持BMP和ICO格式,而且装载进去的图片,必须强制转换成一个预定的大小,如32*32等,对于JPEG格式的图片来说,是不支持的,而通过重载Imagelist控件,使它支持JPEG格式,难度也比较大,所以最后我采用了这种方法:(1)在FROM1上放置一个Image控件,一个Imagelist控件,一个Listview控件。
(2)将Listview1控件与Imagelist1控件关联。
Listview1的LargeImages=ImageList1,Listview1.ViewStyle=vsIcon., Imagelist1的Height和Width都设为120,因为JPEG缩略图的大小通常是120*120的,对于不是这个比例的图片,JPEG缩略图会按比例调节。
(3)使用GDI+的功能,将JPEG缩略图绘制在Image1控件里,这样做之后,Image1里的图片相当于BMP格式的了,即将JPEG缩略图转换成BMP的小图片。
绘制JPEG缩略图代码如下://----------------------------------------------------------------------------------Uese GDIPUTIL,GDIPAPI,GDIPOBJ; //GDI+的DELPHI封装APIconst MAX=120; //缩略图的最大值procedure TForm1.showjpg(fnames:string);V AR Graphics : TGPGraphics;Image, Thumbnail: TGPImage;SZ:double;p:tgppen;i:single; //JPEG缩略图的宽高比W,H:integer; //计算JPEG缩略图的宽与高度beginTRYimage1.Picture :=nil;Image:=TGPImage.Create(fnames);//计算图片宽度和高度,大的=MAX(即120),另一个按比例调整if Image.GetWidth >Image.GetHeight thenbeginW:=MAX;i:=Image.GetWidth /W;i:=Image.getHeight /i;H:=ROUND(I);endELSEBEGINH:=MAX;I:=Image.getHeight /H;i:=Image.getWidth /i;W:=ROUND(I);END;//先绘制一个120*120的白色矩形p:=tgppen.Create(0,2);p.SetColor(makecolor(200,200,200));//-----取JPEG缩略图,绘制到Image1中-------Thumbnail := image.GetThumbnailImage(W, H, nil, nil);Graphics :=TGPGraphics.Create(image1.Canvas.Handle);image1.Canvas.Lock ;graphics.Clear(makecolor(255,255,255));Graphics.DrawImage(Thumbnail, (120-w) div 2, (120-h) div2,Thumbnail.GetWidth,Thumbnail.GetHeight);//给这个图片加个边框graphics.DrawRectangle(p,makerect(0,0,120,120));image1.Canvas.Unlock ;Image.Free;Thumbnail.Free;p.Free;Graphics.Free;except;Image.Free;Thumbnail.Free;p.Free;Graphics.Free;END;end;//------------------------------------------------------------------------------------- (4)将Image1的图片添加到ImageList控件中。
java根据图⽚路径下载图⽚并保存到本地⽬录内容import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import .URL;import .URLConnection;public class DownloadImage {/*** @param args* @throws Exception*/public static void main(String[] args) throws Exception {// TODO Auto-generated method stubdownload("/1/3/B/1_li1325169021.jpg", "1_li1325169021.jpg","d:\\image\\");}public static void download(String urlString, String filename,String savePath) throws Exception {// 构造URLURL url = new URL(urlString);// 打开连接URLConnection con = url.openConnection();//设置请求超时为5scon.setConnectTimeout(5*1000);// 输⼊流InputStream is = con.getInputStream();// 1K的数据缓冲byte[] bs = new byte[1024];// 读取到的数据长度int len;// 输出的⽂件流File sf=new File(savePath);if(!sf.exists()){sf.mkdirs();} // 获取图⽚的扩展名String extensionName = filename.substring(stIndexOf(".") + 1);// 新的图⽚⽂件名 = 编号 +"."图⽚扩展名String newFileName = goods.getProductId()+ "." + extensionName;OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);// 开始读取while ((len = is.read(bs)) != -1) {os.write(bs, 0, len);}// 完毕,关闭所有链接os.close();is.close();}}。
第一种情况:java读取写入图片。
本想找点代码测试一下在SQL Server中存取图片的方法,结果狂搜之后才发现,不是基于在jsp中的应用,就是本身过程太复杂,今天,突然看到一篇java实现数据库图片存储的文章,学java好象也有一年了,学jdbc也很长时间了,可是这方面还没写过呢。
就参考了网上的几篇文章,写了一个下午。
终于写好了。
现在把代码贴出来。
以供大家参考。
代码绝对可以运行,在我的机器是运行的结果完全正确。
我的机器是jdk1.5+winxp+eclipsepackage cn;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;public class PhotoDemo {/*** @param args*/Connection conn=null;public PhotoDemo() {try {String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=master";Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");conn= DriverManager.getConnection(url,"sa","xiaoxin");}catch(SQLException e) {e.printStackTrace();}catch(ClassNotFoundException ce) {ce.printStackTrace();}}public void Insert() {try {String sql="insert into picture values(?,?)";PreparedStatement ps=conn.prepareStatement(sql);File f =new File("E:/PHOTO/baby/1.jpg");FileInputStream input= new FileInputStream(f);ps.setString(1,"cute");ps.setBinaryStream(2, input,(int)f.length());ps.executeUpdate();ps.close();input.close();}catch(SQLException e) {e.printStackTrace();}catch(IOException ie) {ie.printStackTrace();}}public void Read() {try {String sql="select picture from picture where name=?";PreparedStatement ps=conn.prepareStatement(sql);ps.setString(1, "cute");ResultSet rs=ps.executeQuery();byte [] b=new byte[10240*8];while(rs.next()) {InputStream in=rs.getBinaryStream("picture");in.read(b);File f=new File("D:/3.jpg");FileOutputStream out=new FileOutputStream(f);out.write(b, 0, b.length);out.close();}}catch(SQLException e) {e.printStackTrace();}catch(IOException ie) {ie.printStackTrace();}}public static void main(String[] args) {// TODO Auto-generated method stubPhotoDemo p=new PhotoDemo();p.Insert();p.Read();}}其实,很简单的。
图⽚如何存⼊数据库通常对⽤户上传的图⽚需要保存到数据库中。
解决⽅法⼀般有两种:⼀种是将图⽚保存的路径存储到数据库;另⼀种是将图⽚以⼆进制数据流的形式直接写⼊数据库字段中。
以下为具体⽅法: ⼀、保存图⽚的上传路径到数据库: string uppath="";//⽤于保存图⽚上传路径 //获取上传图⽚的⽂件名 string fileFullname = this.FileUpload1.FileName; //获取图⽚上传的时间,以时间作为图⽚的名字可以防⽌图⽚重名 string dataName = DateTime.Now.ToString("yyyyMMddhhmmss"); //获取图⽚的⽂件名(不含扩展名) string fileName = fileFullname.Substring(stIndexOf("\\") + 1); //获取 string type = fileFullname.Substring(stIndexOf(".") + 1); //判断是否为要求的格式 if (type == "bmp" || type == "jpg" || type == "jpeg" || type == "gif" || type == "JPG" || type == "JPEG" || type == "BMP" || type == "GIF") { //将图⽚上传到指定路径的⽂件夹 this.FileUpload1.SaveAs(Server.MapPath("~/upload") + "\\" + dataName + "." + type); //将路径保存到变量,将该变量的值保存到数据库相应字段即可 uppath = "~/upload/" + dataName + "." + type; } ⼆、将图⽚以⼆进制数据流直接保存到数据库: 引⽤如下: using System.Drawing; using System.IO; using System.Data.SqlClient; 设计数据库时,表中相应的字段类型为iamge 保存: //图⽚路径 string strPath = this.FileUpload1.PostedFile.FileName.ToString (); //读取图⽚ FileStream fs = new System.IO.FileStream(strPath, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); byte[] photo = br.ReadBytes((int)fs.Length); br.Close(); fs.Close(); //存⼊ SqlConnection myConn = new SqlConnection("Data Source=.;Initial Catalog=stumanage;User ID=sa;Password=123"); string strComm = " INSERT INTO stuInfo(stuid,stuimage) VALUES(107,@photoBinary )";//操作数据库语句根据需要修改 SqlCommand myComm = new SqlCommand(strComm, myConn); myComm.Parameters.Add("@photoBinary", SqlDbType.Binary, photo.Length); myComm.Parameters["@photoBinary"].Value = photo; myConn.Open(); if (myComm.ExecuteNonQuery() > 0) { bel1.Text = "ok"; } myConn.Close(); 读取: ...连接数据库字符串省略 mycon.Open(); SqlCommand command = new SqlCommand("select stuimage from stuInfo where stuid=107", mycon);//查询语句根据需要修改 byte[] image = (byte[])command.ExecuteScalar (); //指定从数据库读取出来的图⽚的保存路径及名字 string strPath = "~/Upload/zhangsan.JPG"; string strPhotoPath = Server.MapPath(strPath); //按上⾯的路径与名字保存图⽚⽂件 BinaryWriter bw = new BinaryWriter(File.Open(strPhotoPath,FileMode.OpenOrCreate)); bw.Write(image); bw.Close(); //显⽰图⽚ this.Image1.ImageUrl = strPath; 采⽤俩种⽅式可以根据实际需求灵活选择。
java 向数据库中保存图片2007-09-16 16:39Tips :本文中使用 jdk 6.0 + mysql 5.0贴出来好好享受~~~~Part1 : 保存图片到数据库中import java.io.*;import java.sql.*;public class PutImg {public void putimg(String filename) {try {Class.forName("com.mysql.jdbc.Driver").newInstance();Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydefault","root","skychen"); PreparedStatement pstmt = null;String sql = "";File file = new File(filename);InputStream photoStream = new FileInputStream(file);//sql = " UPDATE imgt SET img = ? ";sql = "INSERT INTO imgtable (id,img) VALUES (1,?)";//insert into images(PicNum,Content,Image) values(1,?,?)pstmt = con.prepareStatement(sql);pstmt.setBinaryStream(1,photoStream,(int)file.length());//需获取文件输出流及其大小pstmt.execute();pstmt.close();con.close();} catch (Exception e) {System.err.println("Error");e.printStackTrace();}}public static void main(String[] args){if (!args[0].equals(null)){PutImg pi=new PutImg();pi.putimg(args[0]);System.out.println("Upload file success");}else{System.out.println(args[0]);System.out.println("Warnning: Please type your wanted filename!");}}}Part2 : 保存图片到文件import java.io.*;import java.sql.*;class GetImg {private String URL = "jdbc:mysql://localhost:3306/mydefault?user=root&password=skychen"; private Connection conn = null;private PreparedStatement pstmt = null;private ResultSet rs = null;private File file = null;public void blobRead(String outfilename, int picID) throws Exception {FileOutputStream fos = null;InputStream is = null;byte[] Buffer = new byte[4096];try {Class.forName("com.mysql.jdbc.Driver").newInstance();conn = DriverManager.getConnection(URL);pstmt = conn.prepareStatement("select img from imgtable where id=?");pstmt.setInt(1, picID); // 传入要取的图片的IDrs = pstmt.executeQuery();rs.next();file = new File(outfilename);if (!file.exists()) {file.createNewFile(); // 如果文件不存在,则创建}fos = new FileOutputStream(file); //得到文件输出流is = rs.getBinaryStream("img"); //从数据库中得到文件二进制流int size = 0;while ((size = is.read(Buffer)) != -1) { //读到buffer 中缓存//System.out.println(size); //打印buffer大小fos.write(Buffer, 0, size); //写入到文件输出流中}} catch (Exception e) {System.out.println( e.getMessage());} finally {// 关闭用到的资源fos.close();rs.close();pstmt.close();conn.close();}}public static void main(String[] args) {if (!args[0].equals(null)){try {GetImg gi=new GetImg();gi.blobRead(args[0], 1);} catch (Exception e) {System.out.println("[Main func error: ]" + e.getMessage());}}else{System.out.println("Warnning: Please type your store path and filename!"); }}}类别:J2se | 添加到搜藏 | 浏览(440) | 评论 (1)上一篇:Cannot load JDBC driver class ...下一篇:SQL select 语句使用9则最近读者:登录后,您就出现在这里。
java向数据库存取图片.txt吃吧吃吧不是罪,再胖的人也有权利去增肥!苗条背后其实是憔悴,爱你的人不会在乎你的腰围!尝尝阔别已久美食的滋味,就算撑死也是一种美!减肥最可怕的不是饥饿,而是你明明不饿但总觉得非得吃点什么才踏实。
JAVA向数据库中存取图片的演示在网上看到很多贴子,问JAVA怎样才能将图片存入数据库,并从数据中显示出来。
是啊,我当年也问过这样的问题,也在网上找过,不过都没有一个完整的程序,一个很简单的程序,让我走了很多的弯路,后来写的东西多了,问题就迎刃而解了,现写了一个完整的程序并把源程序贴出来,希望对你了解JAVA这方面的功能有一点帮助。
由于没有写注解,如有什么不能理解的,可以发电子邮件给我(zhliuyou@),同时我也很乐意与喜欢JAVA的朋友们讨论JAVA方面问题:注:本程序的在WINXP+SQLserver2000+JDK1.5测试通过package org.liuyou.insertphotodemo;/*** <p>Title: InsertPhotoDemo</p>* <p>Description: 本程序用于演示向数据库中插入图片及从数据库中读取图片</p>* <p>Copyright: Copyright (c) 2005</p>* <p>Company: LIUYOU STUDIO</p>* @author liuyou(zhliuyou)* @version 1.0*/import java.io.*;import java.sql.*;import javax.swing.*;import java.awt.*;public class InsertPhotoDemo{public static void main(String args[]){JFrame f = new JFrame();JLabel label = new JLabel();try{/* 加载数据库驱动程序 */Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");/* 获取连接,这里用的SQLServer2000*/Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver://10.1.5.110:1433;Database Name=MiniTuiBaoRobot","zhliuyou","zhliuyou");/* 存入图片 */String sql="insert into TEST values(?,?)";PreparedStatement pstmt = con.prepareStatement(sql);File file = new File("e:/study/javafile/InsertPhotoDemo/test.jpg");System.out.println(file.length());FileInputStream fis = new FileInputStream(file);pstmt.setBinaryStream(1,fis,(int)file.length());pstmt.setString(2,"liuyou");pstmt.executeUpdate();pstmt.close();fis.close();/* 读取图片 */byte [] imageByte;String readSql = "select PHOTO from TEST where TESTID=?";PreparedStatement pstm = con.prepareStatement(readSql);pstm.setString(1,"1");ResultSet rs = pstm.executeQuery();if(rs.next()){imageByte = rs.getBytes(1);Image selectPhoto = Toolkit.getDefaultToolkit().createImage(imageByte); ImageIcon icon = new ImageIcon(selectPhoto);label.setIcon(icon);}pstm.close();rs.close();}catch(ClassNotFoundException ex){ex.printStackTrace();}catch(SQLException ex){ex.printStackTrace();}catch(FileNotFoundException ex){ex.printStackTrace();}catch(Exception ex){ex.printStackTrace();}Container contentPane = f.getContentPane(); contentPane.setLayout(new BorderLayout()); contentPane.add(label,BorderLayout.CENTER);f.setTitle("JAVA向数据库中存取图片的演示");f.pack();f.show();}}import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.filechooser.*;import java.io.*;public class FileChooserExample {public static void main(final ng.String[] args) {java.awt.EventQueue.invokeLater(new ng.Runnable(){@Override public void run(){final JFrame frame = new JFrame("FileChooser Example");final DefaultListModel<File> model = new DefaultListModel<>(); final JList<File> list = new JList<>(model);final JToolBar toolbar = new JToolBar();final JFileChooser filechooser = new JFileChooser();filechooser.setMultiSelectionEnabled(true);filechooser.setFileFilter(new FileNameExtensionFilter("JPEG & GIF & PNG Images", "jpg", "jpeg", "gif", "png"));Action select = new AbstractAction("Select ..."){@Override public void actionPerformed(ActionEvent e) { if(JFileChooser.APPROVE_OPTION == filechooser.showOpenDialog(frame)){for(File file: filechooser.getSelectedFiles())model.addElement(file);}}};toolbar.add(select);frame.add(toolbar, BorderLayout.PAGE_START);frame.add(new JScrollPane(list));frame.pack();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);}});}}。
《摘抄1》PostgreSQL 7.4 文档Prev Fast Backward Chapter 31. JDBC 接口 Fast Forward Next31.7. 存储二进制数据PostgreSQL 提供两种不同的方法存储二进制数据。
二进制数据可以使用二进制数据类型bytea存储在表中,或者使用大对象特性,该特性以一种特殊的格式将二进制数据存储在一个独立的表中,然后通过在你的表中保存一个指向该表的类型为 oid 的数值来引用它。
为了判断那种方法比较合适,你必须理解每种方法的局限。
bytea 数据类型并不适合存储非常大数量的二进制数据。
虽然类型为 bytea 的字段可以存储最多 1G 字节的二进制数据,但是这样它会要求数量巨大的内存来处理这样巨大的数值。
存储二进制的大对象的方法更适合存储非常大的数值,但也有自己的局限。
特别是删除一个包含大对象引用的行并未删除大对象。
删除大对象是一个需要执行的独立的操作。
大对象还有一些安全性的问题,因为任何联接到数据库的人都可以查看或者更改大对象,即使他们没有查看/更新包含大对象引用的行的权限也一样。
版本 7.2 是第一个支持 bytea 类型的 JDBC 驱动版本。
在 7.2 中引入的这个功能同时也引入了一个和以往的版本不同的行为。
自 7.2 以来,方法 getBytes(), setBytes(),getBinaryStream() 和 setBinaryStream() 操作 bytea 类型。
在 7.1 和更早的版本里这些方法操作和 OID 类型关联的大对象。
我们可以通过在 Connection 上设置 compatible 属性为数值 7.1 来获取旧的 7.1 的行为。
要使用 bytea 数据类型你只需要使用 getBytes(),setBytes(), getBinaryStream(),或者 setBinaryStream() 方法。
要使用大对象的功能,你可以使用 PostgreSQL JDBC 驱动提供的 LargeObject 类,或者使用 getBLOB() 和 setBLOB() 方法。
我在程序代码里贴了向Mysql数据库写入image代码的程序,可是好多人都是Java的初学者,对于这段代码,他们无法将它转换成jsp,所以我在这在写一下用jsp怎样向数据库写入图像文件。
大家先在数据库建这样一张表,我下面的这些代码对任何数据库都通用,只要支持blob类型的只要大家将连接数据库的参数改一下就可以了。
SQL>create table image(id int,content varchar(200),image blob);如果在sqlserver2000的数据库中,可以将blob字段换为image类型,这在SqlServer2000中是新增的。
testimage.html文件内容如下:<HTML><HEAD><TITLE>Image File </TITLE><meta http-equiv="Content-Type" content="text/html; charset=gb2312"></HEAD><FORM METHOD=POST ACTION="testimage.jsp"><INPUT TYPE="text" NAME="content"><BR><INPUT TYPE="file" NAME="image"><BR><INPUT TYPE="submit"></FORM><BODY></BODY></HTML>我们在Form的action里定义了一个动作testimage.jsp,它的内容如下:<%@ page contentType="text/html;charset=gb2312"%><%@ page import="java.sql.*" %><%@ page import="java.util.*"%><%@ page import="java.text.*"%><%@ page import="java.io.*"%><html><body><%Class.forName("org.gjt.mm.mysql.Driver").newInstance();Stringurl="jdbc:mysql://localhost/mysql?user=root&password=&useUnicode=true&characterEncoding= 8859_1";//其中mysql为你数据库的名字,user为你连接数据库的用户,password为你连接数据库用户的密码,可自己改Connection conn= DriverManager.getConnection(url);String content=request.getParameter("content");String filename=request.getParameter("image");FileInputStream str=new FileInputStream(filename);String sql="insert into test(id,content,image) values(1,?,?)"; PreparedStatement pstmt=dbconn.conn.prepareStatement(sql);pstmt.setString(1,content);pstmt.setBinaryStream(2,str,str.available());pstmt.execute();out.println("Success,You Have Insert an Image Successfully");%>下面我写一个测试image输出的例子看我们上面程序写的对不对,testimageout.jsp的内容如下:<%@ page contentType="text/html;charset=gb2312"%><%@ page import="java.sql.*" %><%@ page import="java.util.*"%><%@ page import="java.text.*"%><%@ page import="java.io.*"%><html><body><%Class.forName("org.gjt.mm.mysql.Driver").newInstance();Stringurl="jdbc:mysql://localhost/mysql?user=root&password=&useUnicode=true&characterEncoding= 8859_1";//其中mysql为你数据库的名字,user为你连接数据库的用户,password为你连接数据库用户的密码,可自己改Connection conn= DriverManager.getConnection(url);String sql = "select image from test where id=1";Statement stmt=null;ResultSet rs=null;try{stmt=conn.createStatement();rs=stmt.executeQuery(sql);}catch(SQLException e){}try {while(rs.next()) {res.setContentType("image/jpeg");ServletOutputStream sout = response.getOutputStream();InputStream in = rs.getBinaryStream(1);byte b[] = new byte[0x7a120];for(int i = in.read(b); i != -1;){sout.write(b);in.read(b);}sout.flush();sout.close();}}catch(Exception e){System.out.println(e);}%></body></html>你运行这个程序,你就会看到刚才你写入美丽的图片就会显示在你面前。
图⽚或⽂件在数据库存储对于图⽚或者⽂件的存储,⽬前主要两种⽅式:1.把图⽚直接以⼆进制形式存储在数据库中; ⼀般数据库提供⼀个⼆进制字段来存储⼆进制数据。
⽐如mysql中有个blob字段。
oracle数据库中是blob或bfile类型。
2.图⽚存储在磁盘上,数据库字段中保存的是图⽚的路径;下⾯详细介绍⼀下这两种存储⽅式。
⼀、图⽚以⼆进制形式直接存储在数据库中: 1.存储实现: ⼤体思路: (1)、将读取到的图⽚⽤程序转化成⼆进制形式; (2)、结合insert into 语句插⼊数据表中的blob类型(bfile类型)字段中去。
(3)、从数据库取出图⽚展⽰的时候。
则是直接发送图⽚内容 2.关于mysql中的blob类型 bolb像int型那样,分为blob、MEDIUMBLOB、LONGBLOB。
其实就是从⼩到⼤, blob 容量为64KB ,MEDIUMBLOB 容量为16M,LONGBLOB 容量为4G。
通常是采⽤语⾔的serialize()函数,将对象序列化以后,存⼊该类型的。
(serialize()返回字符串,此字符串包含了表⽰value的字节流,可以存储于任何地⽅)。
3. 缺点 (1).占⽤与mysql交互的通信时间; (2).图⽚⼀般⽐较⼤,超过1M后,还需要修改mysql中限制通信数据⼤⼩的配置 (3).影响数据库性能,导致限制了整个程序的性能; 4.优点 (1).备份图⽚数据和迁移数据⽅便 图⽚以⼆进制形式存储在数据库,有⼀个好处:备份的时候⽅便。
直接备份数据库,图⽚也跟着备份。
换句话说,迁移环境的时候是⽅便。
⽽图⽚放在磁盘上的话,数据库中存储的只是图⽚路径。
备份数据库后。
磁盘上的图⽚也要跟着备份才⾏。
但是,备份这个好处不是很明显。
图⽚在磁盘上,备份磁盘也没很⼤的事情。
打包压缩也可以了。
互联⽹环境毕竟与传统的软件开发不同,web开发⽐较关注⽹站速度。
也就是数据库的速度。
就像互联⽹开发中,有时候为了速度,⽤空间换时间的做法⽐较普遍,所以往往在设计数据库的时候并不⼀定遵循传统数据库设计三⼤范式。
java 读取并保存excel中的图片收藏/** 保存excel中的图片(以文件形式保存,或者存入数据库)** basePath:应用所在路径,附件存放路径:* 参数:is是上传的附件文件流*/public void saveSheetImgByFile(String basePath,InputStream is) throws ParseException { FileOutputStream os = null;try {Workbook wbk = Workbook.getWorkbook(is);//建文件目录File mkFile = new File(basePath);if (!mkFile.exists() && !mkFile.isDirectory()) {mkFile.mkdirs();}// 循环所有sheetfor (int k = 0; k < wbk.getNumberOfSheets(); k++) {Sheet sheet = wbk.getSheet(k);// 共有多少行int imgNumber = sheet.getNumberOfImages();// 获得sheet所包含的图片数// 循环sheet的所有图片for (int i = 0; i < imgNumber; i++) {Image image = sheet.getDrawing(i);byte[] imageData = image.getImageData();String fileName = image.getImageFile().getName().trim()+ ".jpg";File file = new File(basePath+"/" + fileName);os = new FileOutputStream(file);// 建立一个上传文件的输出流os.write(imageData, 0, imageData.length);// 将文件写入服务器}}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {try {if (os != null) {os.close();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}/** 将excel图片文件保存到数据库*/public void saveSheetImgByDB(InputStream is) throws ParseException,ClassNotFoundException, SQLException, IOException {Class.forName("com.mysql.jdbc.Driver");Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?characterEncoding=utf8", "root", "root");String INSERT_PICTURE = "insert into t_mypicture(name, photo) values (?, ?)";PreparedStatement ps = null;FileOutputStream os = null;try {Workbook wbk = Workbook.getWorkbook(is);// 循环所有sheetfor (int k = 0; k < wbk.getNumberOfSheets(); k++) {Sheet sheet = wbk.getSheet(k);// 共有多少行int imgNumber = sheet.getNumberOfImages();// 获得sheet所包含的图片数// 循环sheet的所有图片for (int i = 0; i < imgNumber; i++) {Image image = sheet.getDrawing(i);byte[] imageData = image.getImageData();String fileName = image.getImageFile().getName().trim() + ".jpg";conn.setAutoCommit(false);ps = conn.prepareStatement(INSERT_PICTURE);ps.setString(1, fileName);ps.setBytes(2, imageData);ps.executeUpdate();mit();}}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {try {if (os != null) {os.close();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}2.action方法调用:ImportExcelUtil ieu = new ImportExcelUtil();ExcelForm excelForm = (ExcelForm) form;FormFile file = excelForm.getExcelFile();// 附件方式保存String basePath = request.getSession().getServletContext().getRealPath( "/")+"excelFile";try {ieu.saveSheetImgByFile(basePath,file.getInputStream());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}// 数据库方式保存try {ieu.saveSheetImgByDB(file.getInputStream());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}引文来源java 读取并保存excel中的图片- LIUJIMMY的专栏- CSDN博客。
往MySQL中存储图⽚的⽅法1 介绍在设计到数据库的开发中,难免要将图⽚或⾳频⽂件插⼊到数据库中的情况。
⼀般来说,我们可以同过插⼊图⽚⽂件相应的存储位置,⽽不是⽂件本⾝,来避免直接向数据库⾥插⼊的⿇烦。
但有些时候,向MySQL中插⼊图⽚更加容易管理。
那么在MySQL中该怎么存储呢?参考资料[1]中有个相当清晰的例⼦,不过是基于MySQL图形界⾯的查询⼯具Query Brower的,你的机⼦上没有安装的话,可能得不到很好的理解。
我在这⾥不在赘述,更详细的资料请看给出的链接吧。
还有,[1]中的例⼦其实只是向我们说明了Query Brower的易⽤和强⼤,对我们在开发中实际应⽤不是很⼤。
所以下⾯就让我们⽤JAVA写⼀个向MySQL中存储的简单实例。
2 建表⾸先,先要在数据库中建表。
我在名为test的数据库下建⽴了⼀个叫pic的表。
该表包括3列,idpic, caption和img。
其中idpic 是主键,caption是对图⽚的表述,img是图像⽂件本⾝。
建表的SQL语句如下:DROP TABLE IF EXISTS `test`.`pic`;CREATE TABLE `test`.`pic` (`idpic` int(11) NOT NULL auto_increment,`caption` varchar(45) NOT NULL default '',`img` longblob NOT NULL,PRIMARY KEY (`idpic`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;将上⾯的语句输⼊到命令⾏中(如果安装了Query Brower,你可以按照参考[1]中的指⽰来建表,那样会更加⽅便。
),执⾏,表建⽴成功。
3 实现图像存储类表完成后,我们就开始写个Java类,来完成向数据库中插⼊图⽚的操作。
我们知道,Java与数据库连接是通过JDBC driver来实现的。
java+mysql实现保存图⽚到数据库,以及读取数据库存储的图⽚⼀:建表⼆:获取数据库连接1:导⼊mysql的驱动jar包,mysql-connector-java-5.1.8-bin.jar2:写代码连接数据库,如下:1/**2 *3*/4 package com.hlcui.file;56 import java.sql.Connection;7 import java.sql.DriverManager;8 import java.sql.SQLException;910/**11 * @author Administrator12 *13*/14public class DBUtil {15// 定义数据库连接参数16public static final String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver";17public static final String URL = "jdbc:mysql://localhost:3306/test";18public static final String USERNAME = "root";19public static final String PASSWORD = "root";2021// 注册数据库驱动22static {23try {24 Class.forName(DRIVER_CLASS_NAME);25 } catch (ClassNotFoundException e) {26 System.out.println("注册失败!");27 e.printStackTrace();28 }29 }3031// 获取连接32public static Connection getConn() throws SQLException {33return DriverManager.getConnection(URL, USERNAME, PASSWORD);34 }3536// 关闭连接37public static void closeConn(Connection conn) {38if (null != conn) {39try {40 conn.close();41 } catch (SQLException e) {42 System.out.println("关闭连接失败!");43 e.printStackTrace();44 }45 }46 }47//测试48public static void main(String[] args) throws SQLException {49 System.out.println(DBUtil.getConn());50 }5152 }三:封装读取图⽚的流1/**2 *3*/4package com.hlcui.file;56import java.io.File;7import java.io.FileInputStream;8import java.io.FileOutputStream;9import java.io.IOException;10import java.io.InputStream;1112/**13 * @author Administrator14 *15*/16public class ImageUtil {1718// 读取本地图⽚获取输⼊流19public static FileInputStream readImage(String path) throws IOException { 20return new FileInputStream(new File(path));21 }2223// 读取表中图⽚获取输出流24public static void readBin2Image(InputStream in, String targetPath) {25 File file = new File(targetPath);26 String path = targetPath.substring(0, stIndexOf("/"));27if (!file.exists()) {28new File(path).mkdir();29 }30 FileOutputStream fos = null;31try {32 fos = new FileOutputStream(file);33int len = 0;34byte[] buf = new byte[1024];35while ((len = in.read(buf)) != -1) {36 fos.write(buf, 0, len);37 }38 fos.flush();39 } catch (Exception e) {40 e.printStackTrace();41 } finally {42if (null != fos) {43try {44 fos.close();45 } catch (IOException e) {46 e.printStackTrace();47 }48 }49 }50 }51 }四:实现图⽚(本地、数据库互相传输)1/**2 *3*/4package com.hlcui.file;56import java.io.FileInputStream;7import java.io.InputStream;8import java.sql.Connection;9import java.sql.PreparedStatement;10import java.sql.ResultSet;11import java.sql.SQLException;1213/**14 * @author Administrator 测试写⼊数据库以及从数据库中读取15*/16public class ImageDemo {1718// 将图⽚插⼊数据库19public static void readImage2DB() {20 String path = "D:/1.png";21 Connection conn = null;22 PreparedStatement ps = null;23 FileInputStream in = null;24try {25 in = ImageUtil.readImage(path);26 conn = DBUtil.getConn();27 String sql = "insert into photo (id,name,photo)values(?,?,?)";28 ps = conn.prepareStatement(sql);29 ps.setInt(1, 1);30 ps.setString(2, "Tom");31 ps.setBinaryStream(3, in, in.available());32int count = ps.executeUpdate();33if (count > 0) {34 System.out.println("插⼊成功!");35 } else {36 System.out.println("插⼊失败!");37 }38 } catch (Exception e) {39 e.printStackTrace();40 } finally {41 DBUtil.closeConn(conn);42if (null != ps) {43try {44 ps.close();45 } catch (SQLException e) {46 e.printStackTrace();47 }48 }49 }5051 }5253// 读取数据库中图⽚54public static void readDB2Image() {55 String targetPath = "D:/image/1.png";56 Connection conn = null;57 PreparedStatement ps = null;58 ResultSet rs = null;59try {60 conn = DBUtil.getConn();61 String sql = "select * from photo where id =?";62 ps = conn.prepareStatement(sql);63 ps.setInt(1, 1);64 rs = ps.executeQuery();65while (rs.next()) {66 InputStream in = rs.getBinaryStream("photo");67 ImageUtil.readBin2Image(in, targetPath);68 }69 } catch (Exception e) {70 e.printStackTrace();71 } finally {72 DBUtil.closeConn(conn);73if (rs != null) {74try {75 rs.close();76 } catch (SQLException e) {77 e.printStackTrace();78 }79 }80if (ps != null) {81try {82 ps.close();83 } catch (SQLException e) {84 e.printStackTrace();85 }86 }8788 }89 }90//测试91public static void main(String[] args) {92//readImage2DB();93 readDB2Image();94 }95 }以上代码均已经验证!。
Mysql数据库中存取图片的Java实现周建儒【摘要】In the application design often needs access to the database image,based on the Java language and Mysql database as an example,the method were introduced. The file in binary code and Base64 code format of data in Mysql database access.%在应用程序设计中经常会遇到需要在数据库中存取图片的情况,以java和Mysql数据库为例,分别介绍了图片文件以二进制和Base64编码的数据格式在Mysql数据库中存取的方法。
【期刊名称】《电子测试》【年(卷),期】2013(000)020【总页数】2页(P89-90)【关键词】图片存储;Base64编码;编码与解码;预编译【作者】周建儒【作者单位】四川信息职业技术学院信息工程系,广元,628040【正文语种】中文图片存储有两种方式:一种是将图片单独存放在固定文件夹里,数据库表中对应的字段仅保存该图片的路径和名字;这种方式实现简单,数据表中无大数据,访问速度快,但是不安全,数据维护不方便。
另一种是先对图片进行编码,再将编码后的数据写到数据库表中,需要时再从数据库表中读出,然后解码生成图片文件;这种方式比较安全,数据维护方便灵活。
本文针对这两种方式,用程序实例进行分析和比较。
1 Mysql数据库MySQL是一个小型关系型数据库管理系统,体积小,速度快,开放源码。
Mysql 支持存储二进制文件的BLOB字段类型;BLOB是个类型系列,包括:TinyBlob、Blob、MediumBlob、LongBlob,它们可容纳的最大字节数分别是255B,65K,16M,4G。
2 预编译语句预编译语句PreparedStatement是java.sql的一个接口,也是Statement的子接口。
java存储图⽚import java.io.File;import java.io.FileOutputStream;import java.io.OutputStream;import java.util.Calendar;import java.util.Random;import javax.servlet.http.HttpServletRequest;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;import sun.misc.BASE64Decoder;public class ImageUntil {public boolean saveBase64File(String username,String imgStr) {// 对字节数组字符串进⾏Base64解码并⽣成图⽚if (imgStr == null) // 图像数据为空return false;imgStr = imgStr.replaceAll("data:image/jpeg;base64,", "");BASE64Decoder decoder = new BASE64Decoder();try {// Base64解码byte[] b = decoder.decodeBuffer(imgStr);for (int i = 0; i < b.length; ++i) {if (b[i] < 0) {// 调整异常数据b[i] += 256;}}// ⽣成jpeg图⽚String fileName=username + ".jpg";HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();File f2=new File(System.getProperty("catalina.home")+ File.separator+"webapps"+File.separator+"uploadFile");boolean exists2 = f2.exists();if(!exists2){f2.mkdirs();}//String realPath=request.getSession().getServletContext().getRealPath("uploadFile/touxiang")+ File.separator;String tomcaturl=System.getProperty("catalina.home")+ File.separator+"webapps"+File.separator+"uploadFile"+File.separator+"touxiang"+ File.separator; File f1=new File(System.getProperty("catalina.home")+ File.separator+"webapps"+File.separator+"uploadFile"+File.separator+"touxiang");boolean exists = f1.exists();if(!exists){f1.mkdirs();}File file = new File(tomcaturl+fileName);OutputStream out = new FileOutputStream(file);out.write(b);out.flush();out.close();return true;} catch (Exception e) {e.printStackTrace();return false;}}}对字节数组字符串进⾏Base64解码并⽣成图⽚,imgData是从客户端发过来的,图⽚经过base64位处理的字符串,并将图⽚存在tomcat服务器根⽬录下。
public class PicCreateCtrl extends HttpServlet{
public PicCreateCtrl(){
super();
}
public void destroy(){
super.destroy();//Just puts"destroy"string in log
//Put your code here
}
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
doPost(request,response);
}
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
response.setContentType("text/html;charset=gb2312");
PrintWriter out=response.getWriter();
SmartUpload mySmartUpload=new SmartUpload();//creat new SmartUpload object long file_size_max=10000000;//the bigest size of file
String fileExt="";
String url="temp/";//the path of save upload file
mySmartUpload.initialize(this.getServletConfig(),request,response);
try{
mySmartUpload.setAllowedFilesList("png,emf,bmp,jpg,gif,BMP,JPG,GIF,PN G,EMF");
//上载文件
mySmartUpload.upload();
}catch(Exception e){
e.printStackTrace();
out.print("<script language=javascript>");
out.println("alert('只允许上传.png,.emf,.bmp,.jpg,.gif类型的图片文件!');");
out.println("window.location='javascript:history.go(-1)'");
out.print("</script>");
}
try{
BaseduManager manager=new BaseduManager();
File myFile=mySmartUpload.getFiles().getFile(0);
String xh=mySmartUpload.getRequest().getParameter("xcxh");
if(myFile.isMissing()){
out.print("<script language=javascript>");
out.println("alert('请先选择你要上传的图片!');");
out.println("window.location='javascript:history.go(-1)'");
out.print("</script>");
}else{
fileExt=myFile.getFileExt();//取得文件后缀名
int file_size=myFile.getSize();//取得文件的大小
String fileurl="";
if(file_size<file_size_max){
//更改文件名,取得当前上传时间的毫秒数值
String rname=Tools.getSystime().substring(0,8);
String filename=myFile.getFileName();
rname=rname+"_"+filename.substring(0,filename.length()-4);
fileurl+=request.getRealPath("/")+url+rname+"."+fileExt;//图片上传后的路径
java.io.File zp=new java.io.File(fileurl);//读入刚才上传的文件
String newurl=request.getRealPath("/")+url+"/"+rname+"_min."+ fileExt;//新的缩略图保存地址
myFile.saveAs(fileurl,mySmartUpload.SAVE_PHYSICAL);
Image src=javax.imageio.ImageIO.read(zp);//构造Image对象
int new_w=320;
int new_h=200;//得到源图长
BufferedImage tag=new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src,0,0,new_w,new_h,null);//绘制缩小后的图
FileOutputStream newimage=new FileOutputStream(newurl);//输出到文件流
JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(newimage);
encoder.encode(tag);//近JPEG编码
newimage.close();
java.io.File sltp=new java.io.File(newurl);//读入刚才上传的文件
manager.saveEduPic(zp,sltp,xh);//把照片和缩略图存到数据库中
out.print("<script language=javascript>");
out.print("alert('图片保存成功!');");
out.print("window.location='javascript:history.go(-1)';");
out.print("</SCRIPT>");
}else{
out.print("<script language=javascript>");
out.print("alert('上传文件大小不能超过"+(file_size_max/1000000)+"M');");
out.println("window.location='javascript:history.go(-1)';");
out.print("</SCRIPT>");
}
}
out.close();
out.flush();
}catch(Exception e){
e.printStackTrace();
}
}
public void init()throws ServletException{ }
}。