Java压缩图片,并粘贴到excel

package picture;

import java.io.File;

import java.io.FileOutputStream;

import net.coobird.thumbnailator.Thumbnails;

public class CompressPicture {

public static void main(String[] args) {

String filePath="D:\\temp\\sreenshot";

double compressPer=0.4f;

try {

changeByDir(filePath,compressPer);

} catch (Exception e) {

e.printStackTrace();

}

}

public static long getFileSize(String filename) {

File file = new File(filename);

if (!file.exists() || !file.isFile()) {

System.out.println("文件不存在");

return -1;

}

return file.length();

}

public static void compressPic(String filePath,String descFileDIr,double compressPer) throws Exception{

String filename ="";

String osName = System.getProperty("os.name");

if (osName.startsWith("Windows")) {

filename =filePath.substring(filePath.lastIndexOf("\\")+1);

} else {

filename =filePath.substring(filePath.lastIndexOf("/")+1);

}

System.out.println("filename: "+filename);

Thumbnails.of(new File(filePath))

.scale(compressPer) //鍥剧墖澶у皬锛堥暱瀹斤級鍘嬬缉 浠�0鎸夌収

.outputQuality(1f) //鍥剧墖璐ㄩ噺鍘嬬缉姣斾緥 浠�0-1锛岃秺鎺ヨ繎1璐ㄩ噺瓒婂ソ

.toOutputStream(new FileOutputStream(descFileDIr+filename));

}

public static String changeByDir(String dirPath, double compressPercent){

File dir = new File(dirPath);

if (!dir.isDirectory()) {

System.err.println("is not a dir");

return "";

}

File[] fileList = dir.listFiles();

String outputFileDir = dir.getAbsolutePath() + "/out/";

File outputFile = new File(outputFileDir);

if (!outputFile.exists() && !outputFile.isDirectory()) {

outputFile.mkdir();

}

for (int i = 0; i <fileList.length;i++) {

File file = fileList[i];

if(!isStringInCaseList(file.getName())){

continue;

}

if (file.getName().endsWith(".png")||file.getName().endsWith(".jpg")) {

try{

compressPic(file.getAbsolutePath(),outputFileDir,compressPercent);

} catch (Exception e) {

e.printStackTrace();

}

}

}

return outputFileDir;

}

public static boolean isStringInCaseList(String data){

boolean result = true;

return result;

}

}

Java粘贴图片到Excel

package picture;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;

import org.apache.poi.ss.usermodel.CellStyle;

import org.apache.poi.xssf.usermodel.*;

import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Comparator;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

public class GenerateExcelReport3 {

private ArrayList<String> wkList= new ArrayList<>();

private ArrayList<String> errorFileNameList= new ArrayList<>();

private CellStyle cellStyle;

public void create_result_report(String folder_path) throws Exception{

List<String> ScreenShotList = getScreenShotAbsolutePathList(folder_path);

try {

for(int i =0;i<wkList.size();i++) {

String filename = folder_path+"\\Result_"+wkList.get(i)+".xlsx";

XSSFWorkbook workbook =new XSSFWorkbook();

XSSFSheet sheet0 = workbook.createSheet();

workbook.setSheetName(0,wkList.get(i));

//sheet0.createRow(0).createCell(0).setCellValue("test");

WritePictureToExcel(ScreenShotList,workbook,wkList.get(i));

FileOutputStream out;

out = new FileOutputStream(filename);

workbook.write(out);

out.flush();

out.close();

}

} catch (Exception e) {

e.printStackTrace();

}

}

public void WritePictureToExcel(List<String> filePaths,XSSFWorkbook workbook,String wkName) {

//获取每个WK的所有casename 和所有WK的path

ArrayList<String> thisWkPictureListPath = new ArrayList<>();

ArrayList<String> caseNameForEachWk = new ArrayList<>();

for(String s:filePaths) {

if(theFileIsMatchWk(s,wkName)) {

thisWkPictureListPath.add(s);

String caseName = getCaseName(s);

if(!caseNameForEachWk.contains(caseName)) {

caseNameForEachWk.add(caseName);

}

}

}

//获取每个case有几个android 图片

HashMap<String, Integer> caseNumberForAndroid = new HashMap<>();

for (int j = 0; j < caseNameForEachWk.size(); j++) {

String caseName = caseNameForEachWk.get(j);

int each_case_count =0;

for (int k = 0; k < thisWkPictureListPath.size(); k++) {

String file_name = getFileNaneFromPath(thisWkPictureListPath.get(k));

if(file_name.contains(caseName)&&file_name.toUpperCase().contains("_AOS_")) {

each_case_count +=1;

}

}

caseNumberForAndroid.put(caseName, each_case_count);

}

//图片粘贴到excel

XSSFSheet sheet =workbook.getSheet(wkName);

int count =0;

for (int j = 0; j < caseNameForEachWk.size(); j++) {

String caseName = caseNameForEachWk.get(j);

XSSFRow row = sheet.createRow(count*30);

//System.out.println("caseName: "+caseName+" count: "+count);

for(String s:thisWkPictureListPath) {

if(getCaseName(s).contains(caseName)) {

PictureWriteToExcel(s,workbook,sheet,count,caseNumberForAndroid,row);

}

}

count +=1;

}

}

public void PictureWriteToExcel(String picture_path,XSSFWorkbook wb,XSSFSheet sheet,int count,

HashMap<String, Integer> caseNumberForAndroid,XSSFRow row) {

String caseName = getCaseName(picture_path);

int addColumnForIOS = 0;

if(caseNumberForAndroid.get(caseName)>0) {

if(isIOSPicture(picture_path)) {

addColumnForIOS = 2;

}

}

int row_index =count;

int column_index =getColumnIndex(picture_path,caseNumberForAndroid)-1;

String pictureName = getPictureNameFromPath(picture_path);

XSSFCell c = row.createCell(column_index*5+addColumnForIOS);

c.setCellValue(pictureName);

//System.out.println(picture_path+" row_index: "+row_index+" column_index: "+column_index);

FileOutputStream fileOut = null;

BufferedImage bufferImg = null;

try {

ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();

bufferImg = ImageIO.read(new File(picture_path));

ImageIO.write(bufferImg, "png", byteArrayOut);

XSSFDrawing patriarch = sheet.createDrawingPatriarch();

/**

* 该构造函数有8个参数

* 前四个参数是控制图片在单元格的位置,分别是图片距离单元格left,top,right,bottom的像素距离

* 后四个参数,前两个表示图片左上角所在的cellNum和 rowNum,后两个参数对应的表示图片右下角所在的cellNum和 rowNum,

* excel中的cellNum和rowNum的index都是从0开始的

*/

XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0,

(short) column_index*5+addColumnForIOS, row_index*30+1, (short) column_index*5+4+addColumnForIOS, row_index*30+27);

patriarch.createPicture(anchor, wb.addPicture(byteArrayOut

.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));

} catch (Exception io) {

io.printStackTrace();

System.out.println("io erorr : " + io.getMessage());

} finally {

if (fileOut != null) {

try {

fileOut.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

public void setCellContent(XSSFRow row,int column_index,String content) {

XSSFCell cell=row.createCell(column_index);

cell.setCellValue(content);

cell.setCellStyle(cellStyle);

}

public List<String> getErrorFileNameList() {

return errorFileNameList;

}

public List<String> getScreenShotAbsolutePathList(String Folder_path) {

List<String> ScreenShotList = new ArrayList<>();

File file = new File(Folder_path);

File[] fs = file.listFiles();

for(File f:fs) {

if(f.getAbsolutePath().endsWith(".png")||f.getAbsolutePath().endsWith(".jpg")||f.getAbsolutePath().endsWith(".jpeg")) {

boolean flag = verifyFileName(getFileNaneFromPath(f.getAbsolutePath()));

if(!flag) {

//System.out.println("error name:"+getFileNaneFromPath(f.getAbsolutePath()));

continue;

}

ScreenShotList.add(f.getAbsolutePath());

System.out.println(f.getAbsolutePath());

getSheetNameFromPath(f.getAbsolutePath());

}

}

wkList.sort(new Comparator<String>() {

public int compare(String s1,String s2) {

return s1.compareTo(s2);

}

});

System.out.println(wkList.toString());

return ScreenShotList;

}

public boolean verifyFileName(String fileName) {

if(!isHave4Single(fileName)) {

errorFileNameList.add(fileName);

return false;

}

try {

Integer.parseInt(getPictureName(fileName).split("_")[4].trim());

} catch (Exception e) {

errorFileNameList.add(fileName);

return false;

}

if(fileName.toUpperCase().contains("_AOS_")||fileName.toUpperCase().contains("_IOS_")) {

}else {

errorFileNameList.add(fileName);

return false;

}

return true;

}

public void getSheetNameFromPath(String path) {

String fileName =getFileNaneFromPath(path);

String caseName = fileName.split("_")[0].trim();

if(!wkList.contains(caseName)) {

wkList.add(caseName.trim());

}

}

public String getPictureName(String file_name) {

return file_name.substring(0,file_name.lastIndexOf("."));

}

public String getPictureNameFromPath(String path) {

String file_name = getFileNaneFromPath(path);

return file_name.substring(0,file_name.lastIndexOf("."));

}

public boolean theFileIsMatchWk(String s,String sheetName) {

String file_name = getFileNaneFromPath(s);

String temp_sheet_name = file_name.split("_")[0];

return sheetName.contains(temp_sheet_name);

}

public String getCaseName(String path) {

String fileName = getFileNaneFromPath(path);

return fileName.split("_")[1].trim();

}

public String getFileNaneFromPath(String f){

String fileName ="";

String osName = System.getProperty("os.name");

if (osName.startsWith("Windows")) {

fileName =f.substring(f.lastIndexOf("\\")+1);

} else {

fileName =f.substring(f.lastIndexOf("/")+1);

}

return fileName;

}

public int getColumnIndex(String path,HashMap<String, Integer> caseNumberForAndroid) {

String caseName = getCaseName(path);

String fileName = getFileNaneFromPath(path);

int index = Integer.parseInt(getPictureName(path).split("_")[4].trim());

if(fileName.toUpperCase().contains("_IOS_")) {

return index + caseNumberForAndroid.get(caseName);

}else {

return index;

}

}

public boolean isHave4Single(String fileName) {

int num = fileName.split("_").length-1;

if(num==4) return true;

return false;

}

public boolean isIOSPicture(String path) {

String fileName = getFileNaneFromPath(path);

if(fileName.toUpperCase().contains("_IOS_")) {

return true;

}else {

return false;

}

}

//public String get_date_string() {

//SimpleDateFormat formatter= new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");

//Date date = new Date(System.currentTimeMillis());

//return formatter.format(date);

//}

//public String get_date2() {

//SimpleDateFormat formatter= new SimpleDateFormat("MM/dd/yyyy");

//Date date = new Date(System.currentTimeMillis());

//return formatter.format(date);

//}

//public CellStyle setStyle(XSSFWorkbook workbook) {

//CellStyle cellStyle = workbook.createCellStyle();

//cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);//设置黑边框

//cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);

//cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);

//cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);

//cellStyle.setWrapText(true);//自动换行

//return cellStyle;

//}

//

//public String listToString(ArrayList<String> list) {

//String s = list.toString();

//return s.substring(1,s.length()-1);

//}

//

//public void getPictureWidthHeight() {

//File picture=new File("C:\\Users\\jeff.xie\\Desktop\\data\\ACBN-79_wealth-024_AOS_1.3.1(776)_1.png");

//try {

//BufferedImage sourceImg = ImageIO.read(new FileInputStream(picture));

//int width=sourceImg.getWidth();

//int height=sourceImg.getHeight();

//System.out.println("width:"+width);

//System.out.println("height:"+height);

//}catch (Exception e){

//e.printStackTrace();

//}

//}

//

//public void getCellHeightWidth(XSSFSheet sheet) {

POI获取单元格的宽和高 ,获取单元格的宽,即获取所在列的宽。先获取单元格所在的sheet:cell.getSheet()

//XSSFCell cell = null;

//XSSFRow row = null;

//sheet.getColumnWidth( cell.getColumnIndex() ); //单位不是像素,是1/256个字符宽度

sheet.getColumnWidthInPixels( cell.getColumnIndex() ); //单位是像素

//

获取单元格的高,即获取所在行的高。先获取单元格所在的row:cell.getRow()

//row.getHeight();

//row.getHeightInPoints();

这两个属性的区别在于HeightInPoints的单位是点,而Height的单位是1/20个点,所以Height的值永远是HeightInPoints的20倍

//}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值