利用数据库如何存入BLOB格式图片,并从数据库中取出BLBO格式图片显示出来

这两天需要在图片存储性能方面做一些实验,无非就是两种方法,一是将图片以BLOB格式存入数据库中,二是将图片路径存入数据库中,然后从数据库中提取出来。

实验数据是从1000张图片中遍历取出100张,样本比较小哈。。。。

下面贴出代码


数据库我使用的是国产达梦数据库,如果要改其他的话也比较简单。


//package lianjie;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.imageio.ImageIO;
public class DmTest {
// 定义 DM JDBC 驱动串
String jdbcString = "dm.jdbc.driver.DmDriver";
// 定义 DM URL 连接串
String urlString = "jdbc:dm://localhost:5236/";
// 定义连接用户名
String userName = "SYSDBA";
// 定义连接用户口令
String password = "SYSDBA";
static //定义sql语句
//String sqlString ="create table yujin3(a int,b int,c int);";
String sqlString1="insert into yujin3  values(123,14,1234);";
// 定义连接对象
static Connection conn = null;


static Statement stmt = null;   
static PreparedStatement ps = null;   
static ResultSet rs = null;  


//private static String sqlString1;
/* 加载 JDBC 驱动程序
* @throws SQLException 异常 */
public void loadJdbcDriver() throws SQLException {
try {
System.out.println("Loading JDBC Driver...");
// 加载 JDBC 驱动程序
//DriverManager.registerDriver(new dm.jdbc.driver.DmDriver()); 
Class.forName(jdbcString);
} catch (ClassNotFoundException e) {
throw new SQLException("Load JDBC Driver Error1: " + e.getMessage());
} catch (Exception ex) {
throw new SQLException("Load JDBC Driver Error : "
+ ex.getMessage());
}
}
public void connect() throws SQLException {
try {
System.out.println("Connecting to DM Server...");
// 连接 DM 数据库
conn = DriverManager.getConnection(urlString, userName, password);
} catch (SQLException e) {
throw new SQLException("Connect to DM Server Error : "
+ e.getMessage());
}
}
/* 关闭连接
* @throws SQLException 异常 */
public void disConnect() throws SQLException {
try {
// 关闭连接
conn.close();
System.out.println("close");
} catch (SQLException e) {
throw new SQLException("close connection error : " + e.getMessage());
}
}

public static void main(String args[]) {

	DmTest basicApp = new DmTest();
	// 加载驱动程序
	try {
		basicApp.loadJdbcDriver();
	} catch (SQLException e2) {
		// TODO Auto-generated catch block
		e2.printStackTrace();
	}
	try {
		basicApp.connect();
	} catch (SQLException e2) {
		// TODO Auto-generated catch block
		e2.printStackTrace();
	}
	
	 String sql = "DROP TABLE blobtest";   
     //String sql=null;
     try {   
          stmt = conn.createStatement();   
         System.out.println(sql);   
        stmt.executeUpdate(sql);   
         //创建表   
         sql = "CREATE TABLE blobtest(" +      
         "b_title int,"+   
         "b_text Blob"+    
         ")";   
     System.out.println(sql);   
     stmt.executeUpdate(sql);   
     System.out.println("创建数据表成功!");   
        
     sql="INSERT INTO blobtest(b_title,b_text)VALUES(?,?)";   
     ps = conn.prepareStatement(sql);   
     //插入图片   
     //File file = new File("F:\\image\\yahoo.jpg");   
     for(int i=0;i<=999;i++)
     {
    	 String s="c:\\images\\"+i+".jpg";
     File file = new File(s);   
     InputStream inputStream = new FileInputStream(file);   
    
     try {   
         ps.setInt(1, i);   
         //新建一byte数组   
         byte[] buf=new byte[inputStream.available()];   
         //将文件读入到byte[]中   
         inputStream.read(buf);   
         ps.setBytes(2, buf);   
         ps.executeUpdate();   
         System.out.println("图片"+i+"插入成功!");   
     } catch (IOException e1) {   
         System.out.println("保存图片到数据库成功!");   
         e1.printStackTrace();   
     }   
        
     }
	 
     
     sql = "SELECT b_title,b_text FROM blobtest";   
     ps = conn.prepareStatement(sql);   
     rs = ps.executeQuery();   
     while(rs.next()){   
    	 if(rs.getInt(1)%10==0){
	         System.out.println("图片名: "+rs.getInt(1));    
	         Blob blob = rs.getBlob("b_text");   
	         String s1="c:\\imagett\\"+rs.getInt(1)+".jpg";
	         File file2 = new File(s1);   
	         OutputStream outputStream = new FileOutputStream(file2);   
	         try {   
	             outputStream.write(blob.getBytes(1,(int)blob.length()));   
	         } catch (IOException e) {   
	             e.printStackTrace();   
	         }   
	         //打印出来的为对象   
	         System.out.println("图片内容: "+ blob.getBinaryStream());  
    	 }
            
     }   
     } catch (SQLException e) {   
         e.printStackTrace();   
     } catch (FileNotFoundException e) {   
         e.printStackTrace();   
     }finally{   
        try {
			basicApp.disConnect();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
     }   
        
 }   
}

然后在相应路径下面就生成了100张图片,速度还是比较快的,关于实验数据大家可以去网上下载,或者减少样本,一两张都可以,只是要稍微修改下代码就行。

转载于:https://my.oschina.net/u/1393676/blog/317093

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Flask 提取 BLOB 数据并显示图片,需要进行以下步骤: 1. 从数据库提取 BLOB 数据。 2. 将 BLOB 数据转换为图片格式。 3. 在 Flask 显示图片。 下面是一个简单的示例代码: ```python from flask import Flask, Response import mysql.connector from PIL import Image from io import BytesIO app = Flask(__name__) # 连接 MySQL 数据库 db = mysql.connector.connect( host="localhost", user="root", password="password", database="test" ) @app.route('/image') def get_image(): # 查询 BLOB 数据 cursor = db.cursor() cursor.execute("SELECT image FROM images WHERE id = 1") data = cursor.fetchone()[0] # 将 BLOB 数据转换为 PIL.Image 对象 image = Image.open(BytesIO(data)) # 将 PIL.Image 对象转换为 JPEG 格式 jpeg_image = BytesIO() image.save(jpeg_image, format='JPEG') # 在 Flask 显示图片 response = Response(jpeg_image.getvalue(), mimetype='image/jpeg') return response if __name__ == '__main__': app.run(debug=True) ``` 在上面的示例代码,我们首先连接到 MySQL 数据库。然后,我们定义了一个路由 `/image`,当用户访问该路由时,我们从数据库提取 BLOB 数据,并将其转换为 PIL.Image 对象。接下来,我们将 PIL.Image 对象转换为 JPEG 格式,并使用 Flask 的 `Response` 类将其发送回客户端。 请注意,上面的示例代码只是一个简单的示例,实际情况可能需要进行更多的错误处理和优化。同时,我们也可以使用其他库来完成类似的操作,例如 SQLAlchemy 和 Pillow 等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值