① 使用java语言操作,如何来实现MySQL中Blob字段的存取
/**
* Title: BlobPros.java
* Project: test
* Description: 把图片存入mysql中的blob字段,并取出
* Call Mole: mtools数据库中的tmp表
* File: C:downloadsluozsh.jpg
* Copyright: Copyright (c) 2003-2003
* Company: uniware
* Create Date: 2002.12.5
* @Author: ChenQH
* @version 1.0 版本*
*
* Revision history
* Name Date Description
* ---- ---- -----------
* Chenqh 2003.12.5 对图片进行存取
*
* note: 要把数据库中的Blob字段设为longblob
*
*/
//package com.uniware;
import java.io.*;
import java.util.*;
import java.sql.*;
public class BlobPros
{
private static final String URL = "jdbc:mysql://10.144.123.63:3306/mtools?user=wind&password=123&useUnicode=true";
private Connection conn = null;
private PreparedStatement pstmt = null;
private ResultSet rs = null;
private File file = null;
public BlobPros()
{
}
/**
* 向数据库中插入一个新的BLOB对象(图片)
* @param infile 要输入的数据文件
* @throws java.lang.Exception
*/
public void blobInsert(String infile) throws Exception
{
FileInputStream fis = null;
try
{
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
conn = DriverManager.getConnection(URL);
file = new File(infile);
fis = new FileInputStream(file);
//InputStream fis = new FileInputStream(infile);
pstmt = conn.prepareStatement("insert into tmp(descs,pic) values(?,?)");
pstmt.setString(1,file.getName()); //把传过来的第一个参数设为文件名
//pstmt.setBinaryStream(2,fis,(int)file.length()); //这种方法原理上会丢数据,因为file.length()返回的是long型
pstmt.setBinaryStream(2,fis,fis.available()); //第二个参数为文件的内容
pstmt.executeUpdate();
}
catch(Exception ex)
{
System.out.println("[blobInsert error : ]" + ex.toString());
}
finally
{
//关闭所打开的对像//
pstmt.close();
fis.close();
conn.close();
}
}
/**
* 从数据库中读出BLOB对象
* @param outfile 输出的数据文件
* @param picID 要取的图片在数据库中的ID
* @throws java.lang.Exception
*/
public void blobRead(String outfile,int picID) throws Exception
{
FileOutputStream fos = null;
InputStream is = null;
byte[] Buffer = new byte[4096];
try
{
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
conn = DriverManager.getConnection(URL);
pstmt = conn.prepareStatement("select pic from tmp where id=?");
pstmt.setInt(1,picID); //传入要取的图片的ID
rs = pstmt.executeQuery();
rs.next();
file = new File(outfile);
if(!file.exists())
{
file.createNewFile(); //如果文件不存在,则创建
}
fos = new FileOutputStream(file);
is = rs.getBinaryStream("pic");
int size = 0;
/* while(size != -1)
{
size = is.read(Buffer); //从数据库中一段一段的读出数据
//System.out.println(size);
if(size != -1) //-1表示读到了文件末
fos.write(Buffer,0,size);
} */
while((size = is.read(Buffer)) != -1)
{
//System.out.println(size);
fos.write(Buffer,0,size);
}
}
catch(Exception e)
{
System.out.println("[OutPutFile error : ]" + e.getMessage());
}
finally
{
//关闭用到的资源
fos.close();
rs.close();
pstmt.close();
conn.close();
}
}
public static void main(String[] args)
{
try
{
BlobPros blob = new BlobPros();
//blob.blobInsert("C:Downloadsluozsh1.jpg");
blob.blobRead("c:/downloads/1.jpg",47);
}
catch(Exception e)
{
System.out.println("[Main func error: ]" + e.getMessage());
}
}
}
② java blob
java blob是什么,让我们一起了解一下?
Blob是计算机视觉图像中的一块连通区域,Blob分析的就是对前景或背景分离后的二值图像,进行连通域提取和标记以及计算Blob的一些相关特征,而且通过Blob提取,还可以获得相关区域的信息。
Blob分析的重要一个步骤是连通区域的确定,那么它的优缺点是什么?
优点:
Blob在目标跟踪的优势有:
1、通过Blob提取,可以获得相关区域的信息,这些信息可以作为边缘监测器或者角点检测器的补充信息。在目标识别中,Blob可以提供局部的统计信息和外貌信息,这些信息能够为目标识别和跟踪提供依据。
2、可以利用Blob对直方图进行峰值检测。
3、Blob还可以作为纹理分析和纹理识别的基元。
4、通过Blob分析,可以得到目标的个数及其所在区域,在进行目标匹配时,不需要对全局图像进行搜索。
缺点:
1、速度过慢,要整个区域作逐点扫描。
2、Blob分析难度大。这是一纯几何学上的问题,一个不规则的形状,如何计算它的面积、大小没有简单易行的算法,太过复杂,运算时间就长,速度就更慢了。
3、实际应用。Blob算法在实际应用中,非常依赖光源。几乎可以说,Blob算法如果离开了一个可靠的光源设计,则完全不起作用。
那么java是怎样对Blob读写的?示例如下:
package com.you.sister; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Properties; public class BlobTest { public static Connection conn; public static Connection getConn() throws Exception { FileInputStream fis = new FileInputStream(new File("jdbc.properties")); Properties prop = new Properties(); prop.load(fis); String driver = prop.getProperty("jdbc.driver"); String url = prop.getProperty("jdbc.url"); String username = prop.getProperty("jdbc.username"); String password = prop.getProperty("jdbc.password"); Class.forName(driver); return DriverManager.getConnection(url, username, password); } public static void main(String[] args) throws Exception { conn = getConn(); readBlob(); writeBlob(); conn.close(); } /** * 从数据库中读大对象出来 * 保存在本地 */ public static void readBlob() { try { String readSql = "select * from emp where empno = ?"; PreparedStatement ps = conn.prepareStatement(readSql); ps.setInt(1, 7369); ResultSet rs = ps.executeQuery(); while (rs.next()) { Blob image = rs.getBlob("image"); DataOutputStream dos = // 在FileOutputStream中指定文件输出路径 new DataOutputStream(new FileOutputStream(7369 + "_image.jpeg")); InputStream fis = image.getBinaryStream(); int out; byte[] outByte = new byte [100]; // 将blob对象输入流写入本地输出流中 while ((out = fis.read(outByte)) != -1) { dos.write(outByte); } fis.close(); dos.flush(); dos.close(); } rs.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 将大对象文件保存进数据库中 */ public static void writeBlob() { try { BufferedInputStream fis = new BufferedInputStream(new FileInputStream(new File("D:\\Tulips.jpg"))); // 如果是新插入字段,则将大对象对应字段插入为empty_clob(); // 如果是修改,则可以先update 该行数据,将大对象对应字段设置为empty_clob(); String writeSql = "select * from emp where empno = ? for update"; PreparedStatement ps = conn.prepareStatement(writeSql); ps.setInt(1, 7499); conn.setAutoCommit(false); ResultSet rs = ps.executeQuery(); while (rs.next()) { oracle.sql.BLOB image = (oracle.sql.BLOB)rs.getBlob("image"); BufferedOutputStream bos = new BufferedOutputStream(image.getBinaryOutputStream()); int c; // 将实际文件中的内容以二进制的形式来输出到blob对象对应的输出流中 while ((c = fis.read()) != -1) { bos.write(c); } fis.close(); bos.close(); } conn.commit(); rs.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } }
③ java中多张blob图片如何在前台预览,要求这些图片同时显示,最好有代码
//您好,提问者:
比如您后台查询的是个List集合数组,前台接受。
List<String>list=newArrayList<String>();//import你懂的
list.add("D:\xx.jpg");//我不是查询数据库,手动添加图片地址,你也懂的
list.add("D:\xx1.jpg");
//这个时候如果struts2的话list是public有setget的话肯定前台能拿到
//如果不是就放到request.setAttribute("list",list);中
这下面是页面代码:
<%
Listlist=request.getAttribute("list");
for(inti=0;i<list.size();i++){%>
<imgsrc="<%=list.get(i)%>"/>
<%}%>
④ 用JAVA怎样将保存在数据库BLOB类型的图片取出来转换为图片然后在页面展示啊
呵呵,这个是没有办法接受哦。
request.setCharacterEncoding("UTF-8");
response.setContentType("image/jpeg");
response.getOutputStream().write(bytes);
这几个参数是把这个图片直接发给浏览器,说白了就直接把图片当成文件让浏览器下载。
解决办法:
<img border=0 src="localhost:8080/Pic" />
localhost:8080是你配置WEB.XML
Pic是你的Servlet类名。
⑤ java如何把图片转换成二进制并存到oracle的blob中,求代码
importjavax.imageio.ImageIO;
importjava.awt.image.BufferedImage;
importjava.io.ByteArrayInputStream;
importjava.io.ByteArrayOutputStream;
importjava.io.File;
importjava.io.IOException;
publicclassImageUtils{
publicstaticvoidmain(String[]args){
Stringstr=img2Binary("C:\Users\hny\Desktop\favicon.jpg");
System.out.println(str);
binary2Img("C:\Users\hny\Desktop\favicon2.jpg",str);
}
/**
*图片转二进制字符串
*
*@parampath图片路径
*@return
*/
publicstaticStringimg2Binary(Stringpath){
Filefile=newFile(path);
if(!file.exists()){
returnnull;
}
try{
BufferedImagebi=ImageIO.read(file);
ByteArrayOutputStreambaos=newByteArrayOutputStream();
Stringsuffix=getSuffix(path);
ImageIO.write(bi,suffix,baos);
byte[]bytes=baos.toByteArray();
returnnewsun.misc.BASE64Encoder().encodeBuffer(bytes).trim();
}catch(IOExceptione){
e.printStackTrace();
}
returnnull;
}
/**
*字符串转图片文件
*
*@parampath图片路径
*@paramimgBinary图片字符串
*/
publicstaticvoidbinary2Img(Stringpath,StringimgBinary){
try{
Filefile=newFile(path);
byte[]bytes1=newsun.misc.BASE64Decoder().decodeBuffer(imgBinary);
ByteArrayInputStreams=newByteArrayInputStream(bytes1);
BufferedImagebi1=ImageIO.read(s);
Stringsuffix=getSuffix(path);
ImageIO.write(bi1,suffix,file);
}catch(IOExceptione){
e.printStackTrace();
}
}
/**
*获取图片后缀名
*
*@parampath
*@return
*/
privatestaticStringgetSuffix(Stringpath){
intindex=path.contains(".")?path.lastIndexOf("."):-1;
if(index>-1){
returnpath.substring(index+1);
}
returnnull;
}
}
⑥ java数据库中blob字段插入图片的问题
ORACLE好像不支持blob存多个值,你可以另外建立一张表叫image_tab两个字段一个是主键id,还有一个就是image(blob只存一张图片信息).然后你这张表字段中存image_tab的主键,如果有多个可以这样1,2,3...用逗号隔开。
⑦ java提取数据库中blob类型的图片,如何全部显示在jsp页面
在OracleQueryBean类中增加一个函数,来进行读取,具体代码如下:
/**
* 根据图片在数据库中的ID进行读取
* @param strID 图片字段ID
* @param w 需要缩到的宽度
* @param h 需要缩到高度
* @return
*/
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;
}
页面使用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();
}
%>