const fs = require('fs');
const path = require('path');
//npm install sharp
const sharp = require('sharp')
const imageDiff = require('image-diff')
const {
JSDOM
} = require('jsdom');
const {
window
} = new JSDOM();
const {
document
} = window;
// const sourceDir = path.join(__dirname, 'A');
const sourceDir = path.dirname(__dirname) + '\古风';
console.log('-----源文件夹路径-----', sourceDir)
// 目标文件夹路径
// const targetDir = path.join(__dirname, 'targetDir');
const targetDir = path.dirname(__dirname) + '\targetDir';
console.log('-----目标文件夹路径-----', targetDir)
// 确保目标文件夹存在,如果不存在则创建
if (!fs.existsSync(targetDir)) {
fs.mkdirSync(targetDir, {
recursive: true
});
}
console.log('**********分割线*************', targetDir)
// 读取源文件夹中的所有文件
fs.readdir(sourceDir, (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
console.log(files)
// const newImgPath = path.join(sourceDir, files[0]);
getBufferArr(files)
});
/**
- @param {Object} files判断两张图片是否一样
*/
async function getBufferArr(files) {
let sameImgNameArr = []
let ImgBufferArr = []
for (var i = 0; i < files.length; i++) {
console.log(第一步---${i}---${files.length})
const newImgPath = path.join(sourceDir, files[i]);
let newImgBuffer = await sharp(newImgPath).resize(8, 8).raw().toBuffer()
ImgBufferArr.push(newImgBuffer.toJSON().data.toString())
}
ImgBufferArr = findDuplicates(ImgBufferArr)
getCutImageFun(ImgBufferArr, files)
}
async function getCutImageFun(ImgBufferArr, files) {
for (var i = 0; i < files.length; i++) {
console.log(第二步---${i}---${files.length})
let fileName = files[i]
const newImgPath = path.join(sourceDir, fileName);
let newImgBuffer = await sharp(newImgPath).resize(8, 8).raw().toBuffer()
let newImgBufferStr = newImgBuffer.toJSON().data.toString()
if (ImgBufferArr.includes(newImgBufferStr)) {
const sourceFilePath = path.join(sourceDir, fileName);
const targetFilePath = path.join(targetDir, fileName);
fs.rename(sourceFilePath, targetFilePath, (err) => {
if (err) {
console.log("333出错了!!!")
return;
}
});
}
}
}
// js 获取数组里面重复的元素
function findDuplicates(arr) {
let seen = new Set();
let duplicates = [];
for (let num of arr) {
if (seen.has(num)) {
duplicates.push(num);
} else {
seen.add(num);
}
}
return duplicates;
}