我一直有一个想法就是在图片文件本身中存储该图片的说明信息,实际上这种东西早就已经存在了,那就是Exif可交换图像文件格式(英语:Exchangeable image file format,官方简称Exif),可是exif的问题是有的图片不支持,比如png。所以我们自己做一个还是有用的。
本示例使用nodejs编写。
首先是向图片添加信息
const fs=require('fs');
//读取文件并转化为buffer
let imgContent=fs.readFileSync('ces.png');
let bufContent=Buffer.from(imgContent);
//要添加的信息,使用json格式方便格式化和读取
let imgInfo={
name:'九寨沟',
tag:['自然','瀑布','日落'],
group:['分组一','分组二']
};
//将信息json转化为字符串后再转化为buffer
let imgInfoJson=JSON.stringify(imgInfo);
let bufImgInfoJson=Buffer.from(imgInfoJson);
//我们的json格式以{"name":"开头,所以需要这样查找
let offsetIndexOf=bufContent.indexOf('{"name":"');
//计算图片和添加的信息合成后的buffer长度
let bufLength=offsetIndexOf+bufImgInfoJson.length;
//判断图片是否已经添加过信息,添加过信息的不能重复添加信息
if(offsetIndexOf<0){
//没有添加过信息的将图片和信息直接合并
bufContent=Buffer.concat([bufContent,bufImgInfoJson]);
}else{
//添加过信息的,新建一个刚好容纳图片+信息的buffer,并写入旧图片buffer
let bufTmp=Buffer.alloc(bufLength,bufContent);
//从信息位置开始,用新信息覆盖掉旧信息
bufContent=bufTmp.fill(bufImgInfoJson,offsetIndexOf);
}
//写文件
fs.writeFile('ces2.png',bufContent,(err)=>{
if (err) throw err;
console.log('信息写入成功');
})
然后是读取添加信息
const fs=require('fs');
//读取文件并转化为buffer
let content=fs.readFileSync('ces2.png');
const buf1=Buffer.from(content);
//toString()函数兼备将buffer转化为字符串和截取字符串的作用
let c=buf1.toString('utf-8',buf1.indexOf('{"name":"'));
console.log(JSON.parse(c));
使用json在JavaScript中是很好转换和读取的
最后封装为一个函数
const fs=require('fs');
const path=require('path');
function addInfoToImg(url,imgInfo,prefix){
let newfilename=(prefix?prefix+'_':"")+path.basename(url);
let dirname=path.dirname(url);
let newurl=path.join(dirname,newfilename);
let imgContent=fs.readFileSync(url);
let bufContent=Buffer.from(imgContent);
let imgInfoJson=JSON.stringify(imgInfo);
let bufImgInfoJson=Buffer.from(imgInfoJson);
let offsetIndexOf=bufContent.indexOf('{"name":"');
let bufLength=offsetIndexOf+bufImgInfoJson.length;
if(offsetIndexOf<0){
bufContent=Buffer.concat([bufContent,bufImgInfoJson]);
console.log('初次加入信息');
}else{
let bufTmp=Buffer.alloc(bufLength,bufContent);
bufContent=bufTmp.fill(bufImgInfoJson,offsetIndexOf);
console.log('替换旧信息');
}
fs.writeFile(newurl,bufContent,(err)=>{
if (err) throw err;
console.log('信息写入成功');
})
}
addInfoToImg('ces.png',{
name:'从快捷客的计划',
tag:['较简介','得到','咕嘀咕','风格和'],
group:['分组一','分组二'],
title:"房管局客户开发"
});