java向数据库存取图片
- 格式:doc
- 大小:38.50 KB
- 文档页数:5
java根据图⽚路径下载图⽚并保存到本地⽬录内容import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import .URL;import .URLConnection;public class DownloadImage {/*** @param args* @throws Exception*/public static void main(String[] args) throws Exception {// TODO Auto-generated method stubdownload("/1/3/B/1_li1325169021.jpg", "1_li1325169021.jpg","d:\\image\\");}public static void download(String urlString, String filename,String savePath) throws Exception {// 构造URLURL url = new URL(urlString);// 打开连接URLConnection con = url.openConnection();//设置请求超时为5scon.setConnectTimeout(5*1000);// 输⼊流InputStream is = con.getInputStream();// 1K的数据缓冲byte[] bs = new byte[1024];// 读取到的数据长度int len;// 输出的⽂件流File sf=new File(savePath);if(!sf.exists()){sf.mkdirs();} // 获取图⽚的扩展名String extensionName = filename.substring(stIndexOf(".") + 1);// 新的图⽚⽂件名 = 编号 +"."图⽚扩展名String newFileName = goods.getProductId()+ "." + extensionName;OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);// 开始读取while ((len = is.read(bs)) != -1) {os.write(bs, 0, len);}// 完毕,关闭所有链接os.close();is.close();}}。
Java获取图⽚的⼤⼩、宽、⾼ 1import java.awt.image.BufferedImage;2import java.io.File;3import java.io.FileInputStream;4import java.io.FileNotFoundException;5import java.io.IOException;67import javax.imageio.ImageIO;89public class Picture {10public static void main(String[] args) throws FileNotFoundException, IOException {11 File picture = new File("E:/PrintScreen/StarSky.jpg");12 BufferedImage sourceImg = ImageIO.read(new FileInputStream(picture));1314 System.out.println(String.format("Size: %.1f KB", picture.length()/1024.0));15 System.out.println("Width: " + sourceImg.getWidth());16 System.out.println("Height: " + sourceImg.getHeight());17 }18 }这个没看懂!1import java.io.File;2import java.io.IOException;3import java.util.Iterator;45import javax.imageio.ImageIO;6import javax.imageio.ImageReader;7import javax.imageio.stream.ImageInputStream;89public class Picture {10public static void main(String[] args) {11 String srcPath = "E:/PrintScreen/1.jpg";1213 File file = new File(srcPath);14try {15 Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg");16 ImageReader reader = (ImageReader) readers.next();17 ImageInputStream iis = ImageIO.createImageInputStream(file);18 reader.setInput(iis, true);19 System.out.println("width: " + reader.getWidth(0));20 System.out.println("height: " + reader.getHeight(0));21 } catch (IOException e) {22 e.printStackTrace();23 }24 }25 }##########################################################################注意:图⽚是预先存放在Java Project下的Package中1import java.awt.Image;2import java.awt.image.BufferedImage;3import java.io.IOException;4import .URL;56import javax.imageio.ImageIO;78public class GetImageSize {9public static void main(String[] args) throws IOException {10 BufferedImage bi = null;1112try {13 URL u = GetImageSize.class.getClassLoader().getResource("images/background.png");14 bi = ImageIO.read(u);15 } catch (IOException e) {16 e.printStackTrace();17 }18 Image img = bi;1920 System.out.println(img.getWidth(null));21 System.out.println(img.getHeight(null));22 }23 }。
spring+mybatis下oracle图片存储读取图片存储:java类中public int emergencytest(HttpServletRequest request){String u=this.getClass().getResource("/").getPath();u=u.substring(1, u.indexOf("/WEB-INF"));u=u+"/upload/";//将图片存在webcontent目录下的upload文件夹下,首先要创建upload文件夹File file=new File(u+"1.png");if(file.exists()){InputStream in=null;try {in = new FileInputStream(file);byte[] b=null;try {b = FileCopyUtils.copyT oByteArray(in);} catch (IOException e) {e.printStackTrace();}Map parametermap=new HashMap();if (b == null || b.length == 0) { return 0; }parametermap.put("file",b);Service.insert_test(parametermap);//该函数调用Dao中的insert_test函数,该函数对应mapper中insert_test语句} catch (FileNotFoundException e) {e.printStackTrace();}}return 0;}mapper文件中//pic字段是BLOB类型insert into t_emergency(id,thm_ttle,lay_ttle,createdate,attachment,pic) values('x','x','x',sysdate,'zxx.jpg',#{file,jdbcType=BLOB})图片读取:java类中public int emergency_get_test(HttpServletRequest request,HttpServletResponse response){String id="x";Map resultmap=new HashMap();resultmap=emergencyService.query_test(id);//数据库查询oracle.sql.BLOB blob=(oracle.sql.BLOB)resultmap.get("PIC");response.setContentType("image/png;charset=UTF-8");response.setCharacterEncoding("UTF-8");InputStream inStream=null;OutputStream op = null;byte[] data;long nLen=0;try {try {inStream = blob.getBinaryStream();nLen = blob.length();int nSize = (int) nLen;data = new byte[nSize];inStream.read(data);//将输入流中的数据读到数组中op = response.getOutputStream();op.write(data);//直接显示到网页上op.flush();op.close();inStream.close();} catch (SQLException e) {e.printStackTrace();}} catch (IOException e1) {System.out.println("获取图片数据失败,原因:" + e1.getMessage());}return 0;}}mapper中:。
将图⽚储存在MySQL数据库中的⼏种⽅法通常对⽤户上传的图⽚需要保存到数据库中。
解决⽅法⼀般有两种:1、将图⽚保存的路径存储到数据库;2、将图⽚以⼆进制数据流的形式直接写⼊数据库字段中。
以下为具体⽅法:⼀、保存图⽚的上传路径到数据库: string uppath="";//⽤于保存图⽚上传路径 //获取上传图⽚的⽂件名 string fileFullname = this.FileUpload1.FileName; //获取图⽚上传的时间,以时间作为图⽚的名字可以防⽌图⽚重名 string dataName = DateTime.Now.ToString("yyyyMMddhhmmss"); //获取图⽚的⽂件名(不含扩展名) string fileName = fileFullname.Substring(stIndexOf("\\") + 1); //获取图⽚扩展名 string type = fileFullname.Substring(stIndexOf(".") + 1); //判断是否为要求的格式 if (type == "bmp" || type == "jpg" || type == "jpeg" || type == "gif" || type == "JPG" || type == "JPEG" || type == "BMP" || type == "GIF") { //将图⽚上传到指定路径的⽂件夹 this.FileUpload1.SaveAs(Server.MapPath("~/upload") + "\\" + dataName + "." + type); //将路径保存到变量,将该变量的值保存到数据库相应字段即可 uppath = "~/upload/" + dataName + "." + type; }⼆、将图⽚以⼆进制数据流直接保存到数据库:引⽤如下命名空间:using System.Drawing; using System.IO; using System.Data.SqlClient; 设计数据库时,表中相应的字段类型为iamge 保存: //图⽚路径 string strPath = this.FileUpload1.PostedFile.FileName.ToString (); //读取图⽚ FileStream fs = new System.IO.FileStream(strPath, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); byte[] photo = br.ReadBytes((int)fs.Length); br.Close(); fs.Close(); //存⼊ SqlConnection myConn = new SqlConnection("Data Source=.;Initial Catalog=stumanage;User ID=sa;Password=123"); string strComm = " INSERT INTO stuInfo(stuid,stuimage) VALUES(107,@photoBinary )";//操作数据库语句根据需要修改 SqlCommand myComm = new SqlCommand(strComm, myConn); myComm.Parameters.Add("@photoBinary", SqlDbType.Binary, photo.Length); myComm.Parameters["@photoBinary"].Value = photo; myConn.Open(); if (myComm.ExecuteNonQuery() > 0) { bel1.Text = "ok"; } myConn.Close(); 读取: ...连接数据库字符串省略 mycon.Open(); SqlCommand command = new SqlCommand("select stuimage from stuInfo where stuid=107", mycon);//查询语句根据需要修改 byte[] image = (byte[])command.ExecuteScalar (); //指定从数据库读取出来的图⽚的保存路径及名字 string strPath = "~/Upload/zhangsan.JPG"; string strPhotoPath = Server.MapPath(strPath); //按上⾯的路径与名字保存图⽚⽂件 BinaryWriter bw = new BinaryWriter(File.Open(strPhotoPath,FileMode.OpenOrCreate)); bw.Write(image); bw.Close(); //显⽰图⽚ this.Image1.ImageUrl = strPath; //采⽤这两种⽅式可以根据实际需求灵活选择。
Java实现读取excel中的数据及图⽚⼀、背景需要完成excel数据的读取与落库⼆、实现Java读取excel数据:指定某⼀⾏,读取整列的数据/*如果是xls格式,使⽤HSSFWorkbook,HSSFSheet,HSSFRow来进⾏相关操作如果是xlsx格式,使⽤XSSFWorkbook,XSSFSheet,XSSFRow来进⾏相关操作,⽬前只⽀持xlsx*/public static HashMap readExcelData(String filename, Integer row, Integer column,Integer sheet) throws IOException {//⽤于存储Exce读取数据HashMap<Integer,String> hashMap=new HashMap();("开始读取excel数据");//读取excel数据File file = ResourceUtils.getFile(filename);InputStream inputStream = new FileInputStream(file);XSSFWorkbook xssfWorkbook=new XSSFWorkbook(inputStream);//获取sheet表格,及读取单元格内容XSSFSheet xssfSheet=xssfWorkbook.getSheetAt(sheet);//先将获取的单元格设置为String类型,下⾯使⽤getStringCellValue获取单元格内容Integer cellIndex = 0;while(cellIndex<=column){//第⼀列为空时直接,赋值为空if (xssfSheet.getRow(row)==null || xssfSheet.getRow(row).getCell(cellIndex)==null){hashMap.put(cellIndex,"");cellIndex++;continue;}xssfSheet.getRow(row).getCell(cellIndex).setCellType(CellType.STRING);String stringValue=xssfSheet.getRow(row).getCell(cellIndex).getStringCellValue();hashMap.put(cellIndex,stringValue);cellIndex++;}("readExcelData:{}",hashMap.toString());return hashMap;}Java读取excel图⽚:获取整个excel的图⽚,可以按照指定的⾏和列来定位读取图⽚/*** 获取Excel中的图⽚* @param xssfSheet* @return*/public static Map<String, XSSFPictureData> getPictures(XSSFSheet xssfSheet){Map<String,XSSFPictureData> map=new HashMap<>();List<XSSFShape> list=xssfSheet.getDrawingPatriarch().getShapes();for (XSSFShape shape:list){XSSFPicture picture = (XSSFPicture) shape;XSSFClientAnchor xssfClientAnchor=(XSSFClientAnchor) picture.getAnchor();XSSFPictureData pdata = picture.getPictureData();// ⾏号-列号String key = xssfClientAnchor.getRow1() + "-" + xssfClientAnchor.getCol1();("key数据:{}",key);map.put(key, pdata);}return map;}实际调⽤测试@Testpublic void test() throws IOException, UnirestException {String filename="classpath:file/org.xlsx";File file = ResourceUtils.getFile(filename);InputStream inputStream = new FileInputStream(file);XSSFWorkbook xssfWorkbook=new XSSFWorkbook(inputStream);Map<String, XSSFPictureData> map=getPictures(xssfWorkbook.getSheetAt(0)); String mapKey="3-15";//指定⾏和列XSSFPictureData xssfPictureData= map.get(mapKey);byte[] data =xssfPictureData.getData();FileOutputStream out = new FileOutputStream("/Users/test12.png");out.write(data);out.close();}}jar包版本<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17</version></dependency>。
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"%>"/>搞定。
java 读取并保存excel中的图片收藏/** 保存excel中的图片(以文件形式保存,或者存入数据库)** basePath:应用所在路径,附件存放路径:* 参数:is是上传的附件文件流*/public void saveSheetImgByFile(String basePath,InputStream is) throws ParseException { FileOutputStream os = null;try {Workbook wbk = Workbook.getWorkbook(is);//建文件目录File mkFile = new File(basePath);if (!mkFile.exists() && !mkFile.isDirectory()) {mkFile.mkdirs();}// 循环所有sheetfor (int k = 0; k < wbk.getNumberOfSheets(); k++) {Sheet sheet = wbk.getSheet(k);// 共有多少行int imgNumber = sheet.getNumberOfImages();// 获得sheet所包含的图片数// 循环sheet的所有图片for (int i = 0; i < imgNumber; i++) {Image image = sheet.getDrawing(i);byte[] imageData = image.getImageData();String fileName = image.getImageFile().getName().trim()+ ".jpg";File file = new File(basePath+"/" + fileName);os = new FileOutputStream(file);// 建立一个上传文件的输出流os.write(imageData, 0, imageData.length);// 将文件写入服务器}}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {try {if (os != null) {os.close();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}/** 将excel图片文件保存到数据库*/public void saveSheetImgByDB(InputStream is) throws ParseException,ClassNotFoundException, SQLException, IOException {Class.forName("com.mysql.jdbc.Driver");Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?characterEncoding=utf8", "root", "root");String INSERT_PICTURE = "insert into t_mypicture(name, photo) values (?, ?)";PreparedStatement ps = null;FileOutputStream os = null;try {Workbook wbk = Workbook.getWorkbook(is);// 循环所有sheetfor (int k = 0; k < wbk.getNumberOfSheets(); k++) {Sheet sheet = wbk.getSheet(k);// 共有多少行int imgNumber = sheet.getNumberOfImages();// 获得sheet所包含的图片数// 循环sheet的所有图片for (int i = 0; i < imgNumber; i++) {Image image = sheet.getDrawing(i);byte[] imageData = image.getImageData();String fileName = image.getImageFile().getName().trim() + ".jpg";conn.setAutoCommit(false);ps = conn.prepareStatement(INSERT_PICTURE);ps.setString(1, fileName);ps.setBytes(2, imageData);ps.executeUpdate();mit();}}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {try {if (os != null) {os.close();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}2.action方法调用:ImportExcelUtil ieu = new ImportExcelUtil();ExcelForm excelForm = (ExcelForm) form;FormFile file = excelForm.getExcelFile();// 附件方式保存String basePath = request.getSession().getServletContext().getRealPath( "/")+"excelFile";try {ieu.saveSheetImgByFile(basePath,file.getInputStream());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}// 数据库方式保存try {ieu.saveSheetImgByDB(file.getInputStream());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}引文来源java 读取并保存excel中的图片- LIUJIMMY的专栏- CSDN博客。
数据库应用程序,特别是基于WEB的数据库应用程序,常会涉及到图片信息的存储和显示。
通常我们使用的方法是将所要显示的图片存在特定的目录下,在数据库中保存相应的图片的名称,在JSP中建立相应的数据源,利用数据库访问技术处理图片信息。
但是,如果我们想动态的显示图片,上述方法就不能满足需要了。
我们必须把图片存入数据库,然后通过编程动态地显示我们需要的图片。
实际操作中,可以利用JSP的编程模式来实现图片的数据库存储和显示。
2、建立后台数据库假定处理的是图片新闻,那么我们可以建立相应的数据库及数据表对象。
我们要存取的数据表结构的SQL脚本如下所示:if exists (select * from dbo.sysobjects where id =object_id(N'[dbo].[picturenews]') andOBJECTPROPERTY(id, N'IsUserTable') = 1)drop table [dbo].[picturenews]GOCREATE TABLE [dbo].[picturenews] ([id] [int] IDENTITY (1, 1) NOT NULL ,[image] [image] NULL ,[content] [varchar] (500) COLLATE Chinese_PRC_CI_AS NULL ,[detail] [varchar] (5000) COLLATE Chinese_PRC_CI_AS NULL) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]GO表picturenews中,字段id作为标识,每存储一行数据,自动增加1。
字段image 用于存储图片信息,其数据类型为“image”。
3、向数据库存储二进制图片启动Dreamweaver MX后,新建一个JSP文件。
其代码如下所示。
<%@ page contentType="text/html;charset=gb2312"%><HTML><HEAD><TITLE>存储图片</TITLE></HEAD><body><!-- 下面的窗体将以Post方法,将数据传递给testimage.jsp文件 --><FORM METHOD=POST ACTION="testimage.jsp">新闻标题:<INPUT TYPE="text" NAME="content"><BR>新闻图片:<INPUT TYPE="file" NAME="image"><BR>新闻内容:<TEXTAREA name="txtmail" rows="15" cols="90"style="BORDER-BOTTOM: #000000 1px solid; BORDER-LEFT: #000000 1px solid; BORDER-RIGHT: #000000 1px solid; BORDER-TOP: #000000 1px solid; FONT-SIZE: 9pt;HEIGHT: 200px; WIDTH: 100%" wrap="physical" ></TEXTAREA><br><INPUT TYPE="submit"></form></HTML>将此文件保存为InputImage.jsp文件,其中testimage.jsp文件是用来将图片数据存入数据库的,具体代码如下所示:<%@ page contentType="text/html;charset=gb2312"%><%@ page import="java.sql.*" %><%@ page import="java.util.*"%><%@ page import="java.text.*"%><%@ page import="java.io.*"%><html><body><%Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//加载驱动程序类Connectioncon=DriverManager.getConnection("jdbc:odbc:denglu","sa","sa");//建立数据库联机,其中denglu为数据库名,sa为连接数据库的帐号及密码。
java向数据库存取图片.txt吃吧吃吧不是罪,再胖的人也有权利去增肥!苗条背后其实是憔悴,爱你的人不会在乎你的腰围!尝尝阔别已久美食的滋味,就算撑死也是一种美!减肥最可怕的不是饥饿,而是你明明不饿但总觉得非得吃点什么才踏实。
JAVA向数据库中存取图片的演示
在网上看到很多贴子,问JAVA怎样才能将图片存入数据库,并从数据中显示出来。
是啊,我当年也问过这样的问题,也在网上找过,不过都没有一个完整的程序,一个很简单的程序,让我走了很多的弯路,后来写的东西多了,问题就迎刃而解了,现写了一个完整的程序并把源程序贴出来,希望对你了解JAVA这方面的功能有一点帮助。
由于没有写注解,如有什么不能理解的,可以发电子邮件给我(zhliuyou@),同时我也很乐意与喜欢JAVA的朋友们讨论JAVA方面问题:
注:本程序的在WINXP+SQLserver2000+JDK1.5测试通过
package org.liuyou.insertphotodemo;
/**
* <p>Title: InsertPhotoDemo</p>
* <p>Description: 本程序用于演示向数据库中插入图片及从数据库中读取图片</p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: LIUYOU STUDIO</p>
* @author liuyou(zhliuyou)
* @version 1.0
*/
import java.io.*;
import java.sql.*;
import javax.swing.*;
import java.awt.*;
public class InsertPhotoDemo
{
public static void main(String args[])
{
JFrame f = new JFrame();
JLabel label = new JLabel();
try
{
/* 加载数据库驱动程序 */
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
/* 获取连接,这里用的SQLServer2000*/
Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver://10.1.5.110:1433;Database Name=MiniTuiBaoRobot","zhliuyou","zhliuyou");
/* 存入图片 */
String sql="insert into TEST values(?,?)";
PreparedStatement pstmt = con.prepareStatement(sql);
File file = new File("e:/study/javafile/InsertPhotoDemo/test.jpg");
System.out.println(file.length());
FileInputStream fis = new FileInputStream(file);
pstmt.setBinaryStream(1,fis,(int)file.length());
pstmt.setString(2,"liuyou");
pstmt.executeUpdate();
pstmt.close();
fis.close();
/* 读取图片 */
byte [] imageByte;
String readSql = "select PHOTO from TEST where TESTID=?";
PreparedStatement pstm = con.prepareStatement(readSql);
pstm.setString(1,"1");
ResultSet rs = pstm.executeQuery();
if(rs.next())
{
imageByte = rs.getBytes(1);
Image selectPhoto = Toolkit.getDefaultToolkit().createImage(imageByte); ImageIcon icon = new ImageIcon(selectPhoto);
label.setIcon(icon);
}
pstm.close();
rs.close();
}catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}catch(SQLException ex)
{
ex.printStackTrace();
}catch(FileNotFoundException ex)
{
ex.printStackTrace();
}catch(Exception ex)
{
ex.printStackTrace();
}
Container contentPane = f.getContentPane(); contentPane.setLayout(new BorderLayout()); contentPane.add(label,BorderLayout.CENTER);
f.setTitle("JAVA向数据库中存取图片的演示");
f.pack();
f.show();
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import java.io.*;
public class FileChooserExample {
public static void main(final ng.String[] args) {
java.awt.EventQueue.invokeLater(new ng.Runnable(){
@Override public void run(){
final JFrame frame = new JFrame("FileChooser Example");
final DefaultListModel<File> model = new DefaultListModel<>(); final JList<File> list = new JList<>(model);
final JToolBar toolbar = new JToolBar();
final JFileChooser filechooser = new JFileChooser();
filechooser.setMultiSelectionEnabled(true);
filechooser.setFileFilter(new FileNameExtensionFilter("JPEG & GIF & PNG Images", "jpg", "jpeg", "gif", "png"));
Action select = new AbstractAction("Select ..."){
@Override public void actionPerformed(ActionEvent e) { if(JFileChooser.APPROVE_OPTION == filechooser.showOpenDialog(frame)){
for(File file: filechooser.getSelectedFiles())
model.addElement(file);
}
}
};
toolbar.add(select);
frame.add(toolbar, BorderLayout.PAGE_START);
frame.add(new JScrollPane(list));
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}。