java向数据库存取图片
java根据图片路径下载图片并保存到本地目录

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获取图片的大小、宽、高

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图片存储读取

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中:。
java读取网络照片的方法

if (HttpResult != HttpURLConnection.HTTP_OK) // 不等于 HTTP_OK 说明连接不成功 System.out.print(“fail”); else { int filesize = urlconn.getContentLength(); // 取数据长度 System.out.println(filesize); BufferedInputStream bis=new BufferedInputStream(urlconn.getInputStream()); BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(target)); byte[] buffer = new byte[1024]; //创建存放输入流的缓冲 int num = -1; //读入的字节数 while (true) { num = bis.read(buffer); // 读入到缓冲区 if (num ==-1){ bos.flush(); break; //已经读完 } bos.flush(); bos.write(buffer,0,num); } bos.close(); bis.close(); } } public static void main(String[] args) throws Exception{
java 读取网络照片的方法
大家知道 java 读取网络照片吗?最近一个 Web 项目,需要下载网络图 片,于是又重拾起一些最基础的东西,各种流的数据传递,简单弄了个非常 方便下载网络图片的例子,代码很简单。 import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.HttpURLConnection; import java.URL; import java.URLConnection; /*. *读取网络照片,保存到本地 * */ public class GetUrlImg { public static void getUrlImg(String URLName,String target) throws Exception {//URLName 照片地址 // target 本地地址 int HttpResult = 0; //服务器返回的状态 URL url = new URL(URLName); //创建 URL URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码 urlconn.connect(); HttpURLConnection httpconn = (HttpURLConnection) urlconn; HttpResult = httpconn.getResponseCode(); System.out.println(HttpResult);
将图片储存在MySQL数据库中的几种方法

将图⽚储存在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中的数据及图片

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对象图⽚并显⽰的⽅法本⽂实例讲述了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中如何读取ORACLE中BLOB字段存储的图片

<iframe name="resultframe" id="resultframe" src="<%=imgsrc %>" marginwidth=1 marginheight=1 frameborder=0 width="100" height="115" scrolling="no"></iframe>
}
%>
以上就是这个实例,希望能对大家有所帮助~~~,更希望大家能留下你的意见或者建议,谢谢!!
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import common.utils.DataSourceFactory;
** 当前版本:1.0
** 作 者:李森
** 完成日期:2009-5-12
public class QueryPhoto {
Connection conn =null;
String sql = "";
public byte[] GetImgByteById(int id){
byte[] data = null;
try {
conn = DataSourceFactory.getFactory().getConnection();
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
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);
}
});
}
}。