java如何將圖片以2進位的形式存入資料庫

來源:互聯網
上載者:User
存入圖片 import java.sql.*; import java.io.*; public class InsertImg { public static void main(String args[]) { try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:DBImg"); String sql = "insert into DBImg (image) values (?)"; PreparedStatement pstmt=con.prepareStatement(sql); FileInputStream fi=new FileInputStream("./room.jpg"); pstmt.setBinaryStream(1,fi,fi.available()); pstmt.execute(); fi.close(); pstmt.close(); con.close(); }catch(Exception e){System.out.println(e.getMessage());} } } 把圖片取出輸出到檔案 import java.io.*; import java.sql.*; public class ImgRead { public static void main(String args[]) { try { Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); String url="jdbc:microsoft:sqlserver://BILLGATES:1433"; Connection cn=DriverManager.getConnection(url,"sa","8310"); Statement st=cn.createStatement(); String str = "select img from test where id=1"; ResultSet rs=st.executeQuery(str); rs.next(); InputStream in=rs.getBinaryStream(1); FileOutputStream file = new FileOutputStream("./88.mp3"); byte c[] = new byte[1024]; int r = 0; while ((r = in.read(c)) != -1){ file.write(c,0,r); } file.close(); in.close(); } catch(Exception e) { e.printStackTrace(); } } } 把圖片輸出到JLabel控制項 import java.awt.*; import java.applet.*; import java.awt.image.BufferedImage; import com.sun.image.codec.jpeg.*; import javax.swing.*; import java.sql.*; import java.io.*; public class DisplayImg { public DisplayImg(){ Image img=null; try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:DBImg"); Statement stmt=con.createStatement(); String sql = "select image from DBImg"; ResultSet rs=stmt.executeQuery(sql); rs.next(); InputStream in = rs.getBinaryStream(1); JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in); img=decoder.decodeAsBufferedImage(); rs.close(); con.close(); }catch(Exception e){System.out.println(e.getMessage());} JFrame f=new JFrame(); JLabel label=new JLabel(); ImageIcon icon=new ImageIcon(img); label.setIcon(icon); JScrollPane jsp=new JScrollPane(label); Container content=f.getContentPane(); content.add(jsp); f.setSize(535,400); f.setVisible(true); } public static void main(String args[]){ DisplayImg di=new DisplayImg(); } } 上面的程式資料庫驅動不一致,自行修改一下.其中在Sqlserver中要存放圖片的欄位應選"image"類型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.