java复制图片
- 格式:doc
- 大小:12.00 KB
- 文档页数:1
javapoi导出图⽚到excel⽰例代码本⽂实例为⼤家分享了java使⽤poi导出图⽚到Excel的具体代码,供⼤家参考,具体内容如下代码实现Controller/*** 导出志愿者/⼈才数据* @param talent_type* @return*/@RequestMapping("/exportData")public void exportData(Integer talent_type, HttpServletResponse response) {String fileId = UUID.randomUUID().toString().replace("-", "");Map<String, Object> param = new HashMap<>() ;param.put("talent_type", talent_type) ;try {List<Map<String, Object>> volunteerMapList = volunteerService.getExportData(param) ;String rootPath = SysConfigManager.getInstance().getText("/config/sys/rootPath");String filePath = rootPath + "/" + fileId + ".xlsx" ;volunteerService.exportData(volunteerMapList, filePath) ;// 下载FileInputStream inputStream = null;try{//设置发送到客户端的响应内容类型response.reset();response.setContentLength((int) new File(filePath).length());response.setContentType("application/octet-stream");response.addHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode("⽂件名.xlsx", "UTF-8")+ "\""); //读取本地图⽚输⼊流inputStream = new FileInputStream(filePath);// 循环取出流中的数据byte[] b = new byte[1024];int len;while ((len = inputStream.read(b)) > 0)response.getOutputStream().write(b, 0, len);} finally{if(inputStream != null){inputStream.close();}}logger.debug("导出志愿者/⼈才数据成功!");} catch (Exception e) {e.printStackTrace();logger.error("导出志愿者/⼈才数据异常!");}}Servicepublic void exportData(List<Map<String, Object>> volunteerMapList, String filePath) throws Exception {String[] alias = {"头像", "名称", "个⼈/团体", "志愿者/⼈才", "性别", "⽣⽇", "⼿机号","⾝份证", "省份", "市", "区/县", "详细地址", "邮箱", "政治⾯貌", "学历", "民族","职业", "团队⼈数", "艺术特长", "介绍"};String[] keys = {"photo", "name", "type", "talent_type", "sex", "birth_day", "mobile","idcard", "province", "city", "county", "address", "email", "political","education", "nation", "profession", "member_count", "art_spetiality", "content"};File file = new File(filePath);if (!file.exists()) file.createNewFile();FileOutputStream fileOutput = new FileOutputStream(file);XSSFWorkbook workbook = new XSSFWorkbook();int sheetSize = volunteerMapList.size() + 50;double sheetNo = Math.ceil(volunteerMapList.size() / sheetSize);String photoImgPath = SysConfigManager.getInstance().getText("/config/sys/rootPath") ;for (int index = 0; index <= sheetNo; index++) {XSSFSheet sheet = workbook.createSheet();workbook.setSheetName(index, "⼈才、志愿者" + index);XSSFRow row = sheet.createRow(0);sheet.setColumnWidth(0, 2048);XSSFCell cell;XSSFCellStyle cellStyle = workbook.createCellStyle();XSSFFont font = workbook.createFont();font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);// 居中cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);// 加粗cellStyle.setFont(font);//创建标题for (int i = 0; i < alias.length; i++) {cell = row.createCell(i);cell.setCellValue(alias[i]);cell.setCellStyle(cellStyle);}int startNo = index * sheetSize;int endNo = Math.min(startNo + sheetSize, volunteerMapList.size());cellStyle = workbook.createCellStyle();// 居中cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 写⼊各条记录,每条记录对应excel表中的⼀⾏for (int i = startNo; i < endNo; i++) {int rowNum = i + 1 - startNo ;row = sheet.createRow(rowNum);Map<String, Object> map = (Map<String, Object>) volunteerMapList.get(i);for (int j = 0; j < keys.length; j++) {cell = row.createCell(j);String key = keys[j] ;if (key.equals("photo")){sheet.addMergedRegion(new CellRangeAddress(i + 1,i + 1,i + 1,i + 1)) ;// 头像File photoFile = new File(photoImgPath + map.get(key)) ;if (photoFile.exists()){BufferedImage bufferedImage = ImageIO.read(photoFile) ;ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();ImageIO.write(bufferedImage, "jpg", byteArrayOut);byte[] data = byteArrayOut.toByteArray();XSSFDrawing drawingPatriarch = sheet.createDrawingPatriarch();XSSFClientAnchor anchor = new XSSFClientAnchor(480, 30, 700, 250, (short)0, i + 1, (short) 1, i + 2);drawingPatriarch.createPicture(anchor, workbook.addPicture(data, XSSFWorkbook.PICTURE_TYPE_JPEG)); sheet.setColumnWidth((short)500, (short)500);row.setHeight((short)500);} else {cell.setCellType(XSSFCell.CELL_TYPE_STRING);cell.setCellValue("");}} else {cell.setCellType(XSSFCell.CELL_TYPE_STRING);Object value = map.get(key);cell.setCellValue(value == null ? "" : value.toString());cell.setCellStyle(cellStyle);}}}// 设置列宽for (int i = 1; i < alias.length; i++)sheet.autoSizeColumn(i);// 处理中⽂不能⾃动调整列宽的问题this.setSizeColumn(sheet, alias.length);}fileOutput.flush();workbook.write(fileOutput);fileOutput.close();}// ⾃适应宽度(中⽂⽀持)private void setSizeColumn(XSSFSheet sheet, int size) {for (int columnNum = 0; columnNum < size; columnNum++) {int columnWidth = sheet.getColumnWidth(columnNum) / 256;for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {XSSFRow currentRow;//当前⾏未被使⽤过if (sheet.getRow(rowNum) == null) {currentRow = sheet.createRow(rowNum);} else {currentRow = sheet.getRow(rowNum);}if (currentRow.getCell(columnNum) != null) {XSSFCell currentCell = currentRow.getCell(columnNum);if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {int length = currentCell.getStringCellValue().getBytes().length;if (columnWidth < length) columnWidth = length;}}}columnWidth = columnWidth * 256 ;sheet.setColumnWidth(columnNum, columnWidth >= 65280 ? 6000 : columnWidth);}}以上所述是⼩编给⼤家介绍java poi导出图⽚到excel⽰例代码解整合,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。
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 }。
Java 提取Word中的文本和图片本文将介绍通过Java来提取或读取Word文档中文本和图片的方法。
这里提取文本和图片包括同时提取文档正文当中以及页眉、页脚中的的文本和图片。
使用工具:Spire.Doc for JavaJar文件导入方法(参考):方法1:下载jar文件包。
下载后解压文件,并将lib文件夹下的Spire.Doc.jar文件导入到java程序。
导入效果参考如下:方法2:可通过maven导入。
参考导入方法。
测试文档如下:Java 代码示例(供参考)【示例1】提取Word 中的文本 import com.spire.doc.*; import java.io.FileWriter;import java.io.IOException;public class ExtractText {public static void main(String[] args) throws IOException{//加载测试文档Document doc = new Document();doc.loadFromFile("test.docx");//获取文本保存为StringString text = doc.getText();//将String写入TxtwriteStringToTxt(text,"提取文本.txt");}public static void writeStringToTxt(String content, String txtFileName) throws IOException {FileWriter fWriter= new FileWriter(txtFileName,true);try {fWriter.write(content);}catch(IOException ex){ex.printStackTrace();}finally{try{fWriter.flush();fWriter.close();} catch (IOException ex) {ex.printStackTrace();}}}}文本提取结果:【示例2】提取Word中的图片import com.spire.doc.Document;import com.spire.doc.documents.DocumentObjectType;import com.spire.doc.fields.DocPicture;import com.spire.doc.interfaces.ICompositeObject;import com.spire.doc.interfaces.IDocumentObject;import javax.imageio.ImageIO;import java.awt.image.RenderedImage;import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.Queue;public class ExtractImg {public static void main(String[] args) throws IOException { //加载Word文档Document document = new Document();document.loadFromFile("test.docx");//创建Queue对象Queue nodes = new LinkedList();nodes.add(document);//创建List对象List images = new ArrayList();//遍历文档中的子对象while (nodes.size() > 0) {ICompositeObject node = (ICompositeObject) nodes.poll();for (int i = 0; i < node.getChildObjects().getCount(); i++) {IDocumentObject child = node.getChildObjects().get(i);if (child instanceof ICompositeObject) {nodes.add((ICompositeObject) child);//获取图片并添加到Listif (child.getDocumentObjectType() == DocumentObjectType.Picture) { DocPicture picture = (DocPicture) child;images.add(picture.getImage());}}}}//将图片保存为PNG格式文件for (int i = 0; i < images.size(); i++) {File file = new File(String.format("图片-%d.png", i));ImageIO.write((RenderedImage) images.get(i), "PNG", file);}}}图片提取结果:(本文完)。
4种java文件复制的方法在Java中,复制文件有多种方法,这里提供四种常见的方法:1. 使用``包中的`Files`类这是Java 7及以后版本中推荐的方法,因为它使用了异步I/O操作,性能更好。
```javaimport ;public class FileCopy {public static void main(String[] args) {Path source = ("");Path target = ("");try {(source, target, _EXISTING);} catch (IOException e) {();}}}```2. 使用``包中的`FileInputStream`和`FileOutputStream`这是较旧的方法,适用于较小的文件。
对于大文件,这种方法可能效率较低,因为它一次读取整个文件。
```javaimport ;public class FileCopy {public static void main(String[] args) {File source = new File("");File target = new File("");try (FileInputStream fis = new FileInputStream(source);FileOutputStream fos = new FileOutputStream(target)) {byte[] buffer = new byte[1024];int length;while ((length = (buffer)) > 0) {(buffer, 0, length);}} catch (IOException e) {();}}}```3. 使用``包中的`FileChannel`这也是一种效率较高的方法,适用于大文件。
Java中copy的用法在Java中,copy是一种常见的操作,用于将数据从一个位置复制到另一个位置。
它可以用于复制对象、数组、集合等不同类型的数据。
本文将全面介绍Java中copy的用法,并提供一些示例代码来帮助读者更好地理解。
1. 复制对象在Java中,要复制一个对象,可以使用两种方式:浅拷贝和深拷贝。
1.1 浅拷贝浅拷贝是指将对象的字段值复制到新对象中,但是如果字段是引用类型,那么只会复制引用而不会复制引用指向的对象。
这意味着新旧对象将共享同一个引用对象。
Java提供了Object类中的clone()方法来实现浅拷贝。
要使用该方法,需要实现Cloneable接口并重写clone()方法。
以下是一个示例代码:class Person implements Cloneable {private String name;private int age;// 构造方法和其他方法省略@Overridepublic Object clone() throws CloneNotSupportedException {return super.clone();}}public class Main {public static void main(String[] args) throws CloneNotSupportedException { Person person1 = new Person("Alice", 20);Person person2 = (Person) person1.clone();System.out.println(person1); // 输出:Person@hashcodeSystem.out.println(person2); // 输出:Person@hashcode}}在上面的代码中,Person类实现了Cloneable接口,并重写了clone()方法。
java根据坐标截取图⽚实例代码java 根据坐标截取图⽚实例代码:代码中有不是注释,很好看懂!package com.json.test;import java.awt.Rectangle;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.util.Iterator;import javax.imageio.ImageIO;import javax.imageio.ImageReadParam;import javax.imageio.ImageReader;import javax.imageio.stream.ImageInputStream;public class OperateImage {// ===源图⽚路径名称如:c:\1.jpgprivate String srcpath ;// ===剪切图⽚存放路径名称.如:c:\2.jpgprivate String subpath ;// ===剪切点x坐标private int x ;private int y ;// ===剪切点宽度private int width ;private int height ;public OperateImage() {}public OperateImage( int x, int y, int width, int height) {this .x = x ;this .y = y ;this .width = width ;this .height = height ;}/*** 对图⽚裁剪,并把裁剪完蛋新图⽚保存。
*/public void cut()throws IOException {FileInputStream is = null ;ImageInputStream iis = null ;try {// 读取图⽚⽂件is =new FileInputStream(srcpath);/** 返回包含所有当前已注册 ImageReader 的 Iterator,这些 ImageReader* 声称能够解码指定格式。
Java中实现复制文件或文件夹拷贝一个文件的算法比较简单,当然,可以对它进行优化,比如使用缓冲流,提高读写数据的效率等。
但是在复制文件夹时,则需要利用Flie类在目标文件夹中创建相应的目录,并且使用递归方法。
import java.io.*;/*** 复制文件夹或文件夹*/public class CopyDirectory {// 源文件夹static String url1 = "f:/photos";// 目标文件夹static String url2 = "d:/tempPhotos";public static void main(String args[]) throws IOException {// 创建目标文件夹(new File(url2)).mkdirs();// 获取源文件夹当前下的文件或目录File[] file = (new File(url1)).listFiles();for (int i = 0; i < file.length; i++) {if (file[i].isFile()) {// 复制文件copyFile(file[i],new File(url2+file[i].getName()));}if (file[i].isDirectory()) {// 复制目录String sourceDir=url1+File.separator+file[i].getName();String targetDir=url2+File.separator+file[i].getName();copyDirectiory(sourceDir, targetDir);}}}// 复制文件public static void copyFile(File sourceFile,File targetFile)throws IOException{// 新建文件输入流并对它进行缓冲FileInputStream input = new FileInputStream(sourceFile);BufferedInputStream inBuff=new BufferedInputStream(input);// 新建文件输出流并对它进行缓冲FileOutputStream output = new FileOutputStream(targetFile);BufferedOutputStream outBuff=new BufferedOutputStream(output);// 缓冲数组byte[] b = new byte[1024 * 5];int len;while ((len =inBuff.read(b)) != -1) {outBuff.write(b, 0, len);}// 刷新此缓冲的输出流outBuff.flush();//关闭流inBuff.close();outBuff.close();output.close();input.close();}// 复制文件夹public static void copyDirectiory(String sourceDir, String targetDir)throws IOException {// 新建目标目录(new File(targetDir)).mkdirs();// 获取源文件夹当前下的文件或目录File[] file = (new File(sourceDir)).listFiles();for (int i = 0; i < file.length; i++) {if (file[i].isFile()) {// 源文件File sourceFile=file[i];// 目标文件File targetFile=newFile(new File(targetDir).getAbsolutePath()+File.separator+file[i].getName());copyFile(sourceFile,targetFile);}if (file[i].isDirectory()) {// 准备复制的源文件夹String dir1=sourceDir + "/" + file[i].getName();// 准备复制的目标文件夹String dir2=targetDir + "/"+ file[i].getName();copyDirectiory(dir1, dir2);}}} }。
JAVA中实现剪切,复制,粘贴功能2008-05-12 15:50要用到java.awt.datatransfer包中的Clipboard类import java.awt.*;import java.awt.event.*;import java.awt.datatransfer.*;public class Test extends Frame implements ActionListener { MenuBar menubar; Menu menu;MenuItem copy,cut,paste;TextArea text1,text2;Clipboard clipboard=null;Test(){ clipboard=getToolkit().getSystemClipboard();//获取系统剪贴板。
menubar=new MenuBar();menu=new Menu("Edit"); copy=new MenuItem("copy");cut=new MenuItem ("cut"); paste=new MenuItem ("paste");text1=new TextArea(20,20); text2=new TextArea(20,20);copy.addActionListener(this); cut.addActionListener(this);paste.addActionListener(this);setLayout(new FlowLayout());menubar.add(menu);menu.add(copy); menu.add(cut); menu.add(paste);setMenuBar(menubar);add(text1);add(text2);setBounds(100,100,200,250); setVisible(true);pack();addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}}public void actionPerformed(ActionEvent e){ if(e.getSource()==copy) //拷贝到剪贴板。