Java从数据库中读取Blob对象图片并显示的方法

本文实例讲述了Java从数据库中读取Blob对象图片并显示的方法。分享给大家供大家参考。具体实现方法如下:

第一种方法:

大致方法就是,从数据库中读出Blob的流来,写到页面中去:

代码如下:

Connection conn = DBManager.getConnection();
  String sql = "SELECT picture FROM teacher WHERE id=1";
  PreparedStatement ps = null;
  ResultSet rs = null;
  InputStream is = null;
  OutputStream os = null;
  try {
   ps = conn.prepareStatement(sql);
   rs = ps.executeQuery();
 
   if(rs.next()){
    is = rs.getBinaryStream(1);
   }
 
   response.setContentType("text/html");
   os = response.getOutputStream();
 
   int num;
   byte buf[] = new byte[1024];
 
   while(   (num=is.read(buf))!=-1   ){
    os.write(buf, 0, num);
   }
 
  } catch (SQLException e) {
   e.printStackTrace();
  }
 
  try {
   is.close();
   os.close();
   rs.close();
   ps.close();
  } catch (SQLException e) {
   e.printStackTrace();
}

在页面中:

代码如下:

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<img name="pic" src="<%=basePath+"servlet/DownloadAsStream"%>"/>

搞定。

第二种方法:

整个流程分为四步,连接oracle数据库 -> 读取blob图片字段 -> 对图片进行缩放 ->把图片展示在jsp页面上。

代码如下:

import java.sql.*;
import java.io.*;
 
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.AffineTransformOp;
import java.awt.geom.AffineTransform;
 
public class OracleQueryBean {
    private final String oracleDriverName = "oracle.jdbc.driver.OracleDriver";
    private Connection myConnection = null;
  
    private String strTabName;
  
    private String strIDName;
 
    private String strImgName;
  
    public OracleQueryBean(){
        try{
            Class.forName(oracleDriverName);
        }catch(ClassNotFoundException ex){
            System.out.println("加载jdbc驱动失败,原因:" + ex.getMessage());
        }
    }
  
    public Connection getConnection(){
        try{
        //用户名+密码; 以下使用的Test就是Oracle里的表空间
        //从配置文件中读取数据库信息
        GetPara oGetPara = new GetPara();
        String strIP = oGetPara.getPara("serverip");
        String strPort = oGetPara.getPara("port");
        String strDBName = oGetPara.getPara("dbname");
        String strUser = oGetPara.getPara("user");
        String strPassword = oGetPara.getPara("password");
      
        this.strTabName = oGetPara.getPara("tablename");
        this.strIDName = oGetPara.getPara("imgidname");
        this.strImgName = oGetPara.getPara("imgname");
      
        String oracleUrlToConnect ="jdbc:oracle:thin:@"+strIP+":"+strPort+":"+strDBName;
            this.myConnection = DriverManager.getConnection(oracleUrlToConnect, strUser, strPassword);
        }catch(Exception ex){
            System.out.println("Can not get connection:" + ex.getMessage());
            System.out.println("请检测配置文件中的数据库信息是否正确." );
        }
        return this.myConnection;
    }
}

2. 读取blob字段
 
在OracleQueryBean类中增加一个函数,来进行读取,具体代码如下:

代码如下:

public byte[] GetImgByteById(String strID, int w, int h){
    //System.out.println("Get img data which id is " + nID);
    if(myConnection == null)
         this.getConnection();
    byte[] data = null;
    try {
            Statement stmt = myConnection.createStatement();
            ResultSet myResultSet = stmt.executeQuery("select " + this.strIDName + " from " + this.strTabName + " where " + this.strIDName + "=" + strID);
          
            StringBuffer myStringBuffer = new StringBuffer();
            if (myResultSet.next()) {
                java.sql.Blob blob = myResultSet.getBlob(this.strImgName);
                InputStream inStream = blob.getBinaryStream();
                try {
                    long nLen = blob.length();
                    int nSize = (int) nLen;
                    //System.out.println("img data size is :" + nSize);
                    data = new byte[nSize];
                    inStream.read(data);
                    inStream.close();
                } catch (IOException e) {
                    System.out.println("获取图片数据失败,原因:" + e.getMessage());
                }
              
                data = ChangeImgSize(data, w, h);
            }
            System.out.println(myStringBuffer.toString());
            myConnection.commit();
            myConnection.close();
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
        return data;
}

3. 缩放图片

因为图片的大小可能不一致,但是在页面中输出的大小需要统一,所以需要
在OracleQueryBean类中增加一个函数,来进行缩放,具体代码如下:

代码如下:

private byte[] ChangeImgSize(byte[] data, int nw, int nh){
    byte[] newdata = null;
    try{
         BufferedImage bis = ImageIO.read(new ByteArrayInputStream(data));
            int w = bis.getWidth();
            int h = bis.getHeight();
            double sx = (double) nw / w;
            double sy = (double) nh / h;
            AffineTransform transform = new AffineTransform();
            transform.setToScale(sx, sy);
            AffineTransformOp ato = new AffineTransformOp(transform, null);
            //原始颜色
            BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR);
            ato.filter(bis, bid);
          
            //转换成byte字节
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bid, "jpeg", baos);
            newdata = baos.toByteArray();
          
    }catch(IOException e){
         e.printStackTrace();
    }
    return newdata;
}

4. 展示在页面
页面使用OracleQueryBean来根据用户提供的图片id进行查询,在读取并进行缩放后,通过jsp页面进行展示,具体代码如下:

代码如下:

<%@ page language="java" contentType="text/html;;charset=gbk" %>
<jsp:useBean id="OrcleQuery" scope="page" class="HLFtiDemo.OracleQueryBean" />
<%
    response.setContentType("image/jpeg");
    //图片在数据库中的 ID
    String strID = request.getParameter("id");
    //要缩略或放大图片的宽度
    String strWidth = request.getParameter("w");
    //要缩略或放大图片的高度
    String strHeight = request.getParameter("h");
    byte[] data = null;
    if(strID != null){
        int nWith = Integer.parseInt(strWidth);
        int nHeight = Integer.parseInt(strHeight);
        //获取图片的byte数据
        data = OrcleQuery.GetImgByteById(strID, nWith, nHeight);
        ServletOutputStream op = response.getOutputStream();      
       op.write(data, 0, data.length);
       op.close();
       op = null;
        response.flushBuffer();
        //清除输出流,防止释放时被捕获异常
        out.clear();
        out = pageContext.pushBody();
    }
%>

5. OracleQueryBean查询类的整体代码

OracleQueryBean.java文件代码如下所示:

代码如下:

import java.sql.*;
import java.io.*;
 
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.AffineTransformOp;
import java.awt.geom.AffineTransform;
 
public class OracleQueryBean {
    private final String oracleDriverName = "oracle.jdbc.driver.OracleDriver";
 
    private Connection myConnection = null;
  
  
    private String strTabName;
  
    private String strIDName;
  
    private String strImgName;
  
    public OracleQueryBean(){
        try{
            Class.forName(oracleDriverName);
        }catch(ClassNotFoundException ex){
            System.out.println("加载jdbc驱动失败,原因:" + ex.getMessage());
        }
    }
  
    public Connection getConnection(){
        try{
        //用户名+密码; 以下使用的Test就是Oracle里的表空间
        //从配置文件中读取数据库信息
        GetPara oGetPara = new GetPara();
        String strIP = oGetPara.getPara("serverip");
        String strPort = oGetPara.getPara("port");
        String strDBName = oGetPara.getPara("dbname");
        String strUser = oGetPara.getPara("user");
        String strPassword = oGetPara.getPara("password");
      
        this.strTabName = oGetPara.getPara("tablename");
        this.strIDName = oGetPara.getPara("imgidname");
        this.strImgName = oGetPara.getPara("imgname");
      
        String oracleUrlToConnect ="jdbc:oracle:thin:@"+strIP+":"+strPort+":"+strDBName;
            this.myConnection = DriverManager.getConnection(oracleUrlToConnect, strUser, strPassword);
        }catch(Exception ex){
            System.out.println("Can not get connection:" + ex.getMessage());
            System.out.println("请检测配置文件中的数据库信息是否正确." );
        }
        return this.myConnection;
    }
  
    public byte[] GetImgByteById(String strID, int w, int h){
    //System.out.println("Get img data which id is " + nID);
    if(myConnection == null)
         this.getConnection();
    byte[] data = null;
    try {
            Statement stmt = myConnection.createStatement();
            ResultSet myResultSet = stmt.executeQuery("select " + this.strIDName + " from " + this.strTabName + " where " + this.strIDName + "=" + strID);
          
            StringBuffer myStringBuffer = new StringBuffer();
            if (myResultSet.next()) {
                java.sql.Blob blob = myResultSet.getBlob(this.strImgName);
                InputStream inStream = blob.getBinaryStream();
                try {
                    long nLen = blob.length();
                    int nSize = (int) nLen;
                    //System.out.println("img data size is :" + nSize);
                    data = new byte[nSize];
                    inStream.read(data);
                    inStream.close();
                } catch (IOException e) {
                    System.out.println("获取图片数据失败,原因:" + e.getMessage());
                }
              
                data = ChangeImgSize(data, w, h);
            }
            System.out.println(myStringBuffer.toString());
            myConnection.commit();
            myConnection.close();
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
        return data;
    }

public byte[] GetImgByteById(String strID){
    //System.out.println("Get img data which id is " + nID);
    if(myConnection == null)
         this.getConnection();
    byte[] data = null;
    try {
            Statement stmt = myConnection.createStatement();
            ResultSet myResultSet = stmt.executeQuery("select " + this.strIDName + " from " + this.strTabName + " where " + this.strIDName + "=" + strID);
          
            StringBuffer myStringBuffer = new StringBuffer();
            if (myResultSet.next()) {
                java.sql.Blob blob = myResultSet.getBlob(this.strImgName);
                InputStream inStream = blob.getBinaryStream();
                try {
                    long nLen = blob.length();
                    int nSize = (int) nLen;
                    data = new byte[nSize];
                    inStream.read(data);
                    inStream.close();
                } catch (IOException e) {
                    System.out.println("获取图片数据失败,原因:" + e.getMessage());
                }
            }
            System.out.println(myStringBuffer.toString());
            myConnection.commit();
            myConnection.close();
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
        return data;
    }

private byte[] ChangeImgSize(byte[] data, int nw, int nh){
    byte[] newdata = null;
    try{
         BufferedImage bis = ImageIO.read(new ByteArrayInputStream(data));
            int w = bis.getWidth();
            int h = bis.getHeight();
            double sx = (double) nw / w;
            double sy = (double) nh / h;
            AffineTransform transform = new AffineTransform();
            transform.setToScale(sx, sy);
            AffineTransformOp ato = new AffineTransformOp(transform, null);
            //原始颜色
            BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR);
            ato.filter(bis, bid);         
            //转换成byte字节
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bid, "jpeg", baos);
            newdata = baos.toByteArray();
    }catch(IOException e){
         e.printStackTrace();
    }
    return newdata;
    }
}

下面是我的存储读取blob图片的案例

代码如下:

import java.sql.*;   
import java.io.*;  
public class InsertPhoto { 
    public static void main(String[] args) throws Exception{ 
            Class.forName("com.mysql.jdbc.Driver");   
           Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/wiseweb?user=root&password=root");   
           File f = new File("e:/123.jpg");   
           FileInputStream fis = new FileInputStream(f);   
           String sql = "insert into photo(photo,photoName) values(?,?)";   
           PreparedStatement pstmt = con.prepareStatement(sql);   
           pstmt.setBinaryStream(1,fis,(int)f.length());   
           pstmt.setString(2, "测试图片"); 
           pstmt.executeUpdate();   
           fis.close();   
           pstmt.close();   
           con.close();  
    } 
}

代码如下:

import java.awt.image.BufferedImage; 
import java.io.BufferedInputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 
 
import javax.imageio.ImageIO; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
import com.sun.image.codec.jpeg.JPEGCodec; 
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ReadPhoto extends HttpServlet{ 
 
    private static final long serialVersionUID = 1L; 
     
    public void doGet(HttpServletRequest request, HttpServletResponse response){ 
        if(request.getParameter("id") != null){ 
            response.setContentType("image/jpeg"); 
            try { 
                InputStream is = query_getPhotoImageBlob(Integer.parseInt(request.getParameter("id"))) ; 
                if(is != null){ 
                    is = new BufferedInputStream(is) ; 
                    BufferedImage bi = ImageIO.read(is) ; 
                    OutputStream os = response.getOutputStream() ; 
                    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os) ; 
                    encoder.encode(bi); 
                    os.close();   
                    is.close();   
                } 
            } catch(IOException e){ 
                e.printStackTrace(); 
            }catch (NumberFormatException e) { 
                // TODO Auto-generated catch block 
                e.printStackTrace(); 
            } catch (ClassNotFoundException e) { 
                // TODO Auto-generated catch block 
                e.printStackTrace(); 
            } catch (SQLException e) { 
                // TODO Auto-generated catch block 
                e.printStackTrace(); 
            } 
        } 
    } 
     
    public static InputStream query_getPhotoImageBlob(int id) throws ClassNotFoundException, SQLException{   
           String sql = "select photo from photo where id="+id;   
           Connection con = null;   
           Statement stmt = null;   
           ResultSet rs = null;   
           InputStream result = null;   
           try {   
            Class.forName("com.mysql.jdbc.Driver");   
            con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/wiseweb?user=root&password=root");    
            stmt = con.createStatement();   
            rs = stmt.executeQuery(sql);   
            if (rs.next())   
            result = rs.getBlob("photo").getBinaryStream();   
           } catch (SQLException e) {   
            // TODO: handle exception   
            System.err.println(e.getMessage());   
           }finally{   
               rs.close();   
               stmt.close();   
               con.close();  
           }   
           return result;   
        }  
}

jsp显示

代码如下:

<img style="width:320px;height:240px" src="<%=basePath%>/genImage?id=3"/>

web.xml中配置

代码如下:

<servlet> 
    <servlet-name>genImage</servlet-name> 
    <servlet-class>ReadPhoto</servlet-class> 
</servlet> 
<servlet-mapping> 
    <servlet-name>genImage</servlet-name> 
    <url-pattern>/genImage</url-pattern> 
</servlet-mapping>

希望本文所述对大家的Java程序设计有所帮助。

(0)

相关推荐

  • 详解JAVA生成将图片存入数据库的sql语句实现方法

    详解JAVA生成将图片存入数据库的sql语句实现方法 实现代码: 注释很清楚,不在重述~ public class Image2Hex { public static void main(String[] args) { try{ //存放图片的文件夹 File list = new File("d:/qmx"); File[] lists = list.listFiles(); String name; //生成的语句存放文件 PrintWriter pw = new PrintWr

  • Java+mysql本地图片上传数据库及下载示例

    做一个将本地图片上传到mysql数据库的小实例,顺便也下载下来到桌面检测是否上传成功. 在写代码之前得先在数据库中建立image表,用来存储图片. create table image (id int primary key auto_increment , name varchar(30) COMMENT '名称', content mediumblob COMMENT '图片'); 下面直接上代码: package jdbc_imagetest; import java.io.*; impo

  • Java从数据库中读取Blob对象图片并显示的方法

    本文实例讲述了Java从数据库中读取Blob对象图片并显示的方法.分享给大家供大家参考.具体实现方法如下: 第一种方法: 大致方法就是,从数据库中读出Blob的流来,写到页面中去: 复制代码 代码如下: Connection conn = DBManager.getConnection();   String sql = "SELECT picture FROM teacher WHERE id=1";   PreparedStatement ps = null;   ResultSe

  • 详解python中读取和查看图片的6种方法

    目录 1 OpenCV 2 imageio 3 PIL 4 scipy.misc 5 tensorflow 6 skimage 本文主要介绍了python中读取和查看图片的6种方法,分享给大家,具体如下: file_name1='test_imgs/spect/1.png' # 这是彩色图片 file_name2='test_imgs/mri/1.png' # 这是灰度图片 1 OpenCV 注:用cv2读取图片默认通道顺序是B.G.R,而不是通常的RGB顺序,所以读进去的彩色图直接显示会出现变

  • Java 在PPT中添加文本和图片超链接的实现方法

    在文档中添加超链接,可以快速从当前文档跳转至指定的网页或打开指定的外部文件.前文中我们介绍过如何使用Java程序来为Word文档和Excel工作表添加超链接.本文将演示如何在PPT中添加文本和图片超链接. 使用工具:Free Spire.Presentation for Java(免费版)Jar文件获取及导入: 方法1:通过官网下载获取jar包.解压后将lib文件夹下的Spire.Presentation.jar文件导入Java程序.(如下图) 方法2:通过maven仓库安装导入.具体安装教程参

  • 从Oracle数据库中读取数据自动生成INSERT语句的方法

    Oracle INSERT 语句 方法1 我估计有点 SQL 基础的人都会写 INSERT 语句.下面是 SQL 标准写法. INSERT INTO employees (employee_id, name) VALUES (1, 'Zhangsan'); INSERT INTO employees VALUES (1, 'Shangbo'); 方法2 其实, Oracle 还支持下面的写法,作用和上面的语句完全相同. INSERT INTO (SELECT employee_id, name

  • asp.net mvc 从数据库中读取图片的实现代码

    首先是创建一个类,继承于ActionResult,记住要引用System.Web.Mvc命名空间,如下: 复制代码 代码如下: public class ImageResult : ActionResult { public ImageFormat ContentType { get; set; } public Image image { get; set; } public string SourceName { get; set; } public ImageResult(string _

  • C# 文件保存到数据库中或者从数据库中读取文件

    其实,方法非常的简单,只是可能由于这些朋友刚刚开始编程不久,一时没有找到方法而已.下面介绍一下使用C#来完成此项任务. 首先,介绍一下保存文件到数据库中. 将文件保存到数据库中,实际上是将文件转换成二进制流后,将二进制流保存到数据库相应的字段中.在SQL Server中该字段的数据类型是Image,在Access中该字段的数据类型是OLE对象. 复制代码 代码如下: //保存文件到SQL Server数据库中 FileInfo fi=new FileInfo(fileName); FileStr

  • C# 制作PictureBox圆形头像框并从数据库中读取头像

    现在只要是有关头像的框基本都是圆形的了,C#提供的PictureBox控键默认情况下是方形的非常大的影响美观 PictureBox默认情况下 比起上面的还是有一点不太好看的- 使用C#提供的类进行圆形: 工具箱拉出PictureBox 设置图片的显示模式为ZOOM 特别注意: 框的比例必须为一样不然会变椭圆的 窗体加载时: pictureBox1.Image = Image.FromFile(@"C:\Users\Administrator\Desktop\1.png"); 为了方便演

  • php从数据库中读取特定的行(实例)

    有的时候我们需要从数据库中读取特定的数据,来检验用户的输入,这个时候需要执行的sql语句是: select * from table_name where id='num'; 需要执行这样的一个语句. 那么怎样来执行这样的语句. 为了执行sql语句,我们需要和数据库相连接 <?PHP $servername='localhost'; $username="root"; $password="1234"; $dbname="mydb1"; /

  • java导出数据库中Excel表格数据的方法

    本篇文章基于java把数据库中的数据以Excel的方式导出,欢迎各位大神吐槽: 1.基于maven jar包引入如下: <dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>jxl</artifactId> <version>2.6.12</version> </dependency> 2.首先创建数据库对应的实体类VO :U

  • python spyder中读取txt为图片的方法

    有时候需要将一个环境中的图片可视化,但是可能这个环境下不方便,因此需要将这个环境下的图像数据保存下来,然后在另一个环境下查看,比如,有一个图像数据,image.txt,里面的数据是图像的像素值,范围是0-255,像素值之间以空格键分开,行与行之间是回车键分开,那么在Python Spyder环境下通过简单的几条语句就搞定: import numpy from skimage import io image = numpy.loadtxt("image.txt") io.imshow(i

随机推荐