java从数据库中读取图片到Jpanel(用BufferedImage)

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.imageio.ImageIO;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.image.BufferedImage;


public class pictest
{
public pictest(){
JFrame f=new JFrame();
   Container p=f.getContentPane();
ppic pic=null;
InputStream in=null;
try{
int i=3;
String url="****************";
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(url,"***","***");
//连接到数据库
if(!con.isClosed())
System.out.println("数据库连接成功");
String sql="select * from campusimage";
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(sql);


for(int j=0;j rs.next();
if(rs.next())
in=rs.getBinaryStream(1);
            pic=new ppic(in);
rs.close();
st.close();
con.close();
}catch(Exception e){e.printStackTrace();}
p.setLayout(null);
p.add(pic);
f.setBounds(500,400,800,900);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}


class ppic extends JPanel
{   BufferedImage bi;
ppic(InputStream in){
try{
 bi=ImageIO.read(in);
 setBounds(0,0,700,600);
}catch(Exception e){e.printStackTrace();}
}
public void paint(Graphics g){
g.drawImage(bi,0,0,700,600,null);
}
}
public static void main(String[] args){
new pictest();
}


}

ps:网上许多人都是把数据库中的图片实例化到本地,不仅读取速度慢,而且浪费内存,当时如果你的图片非常小就算了。

你可能感兴趣的:(java)