最近公司有个项目,要抓取客户微信公众号的文章,以及文章内容中的图片,而且在图片加上客户本身的水印。咱们使用阿里云OSS存储图片和加水印,发现真心好用,提高了咱们的开发效率,阿里云如今是愈来愈强大了...... 不废话,继续正题......html
本来想得很简单,gif图片不打水印,其它图片格式都加。判断文件类型的方法,参考了园子里的作法:sql
http://www.cnblogs.com/babycool/p/3531696.html浏览器
/// <summary> /// 判断文件格式 /// http://www.cnblogs.com/babycool /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static bool IsAllowedExtension(string filePath) { FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read); BinaryReader reader = new BinaryReader(stream); string fileclass = ""; // byte buffer; try { //buffer = reader.ReadByte(); //fileclass = buffer.ToString(); //buffer = reader.ReadByte(); //fileclass += buffer.ToString(); for (int i = 0; i < 2; i++) { fileclass += reader.ReadByte().ToString(); } } catch (Exception) { throw; } if (fileclass == "255216") { return true; } else { return false; } /*文件扩展名说明 * 255216 jpg * 208207 doc xls ppt wps * 8075 docx pptx xlsx zip * 5150 txt * 8297 rar * 7790 exe * 3780 pdf * * 4946/104116 txt * 7173 gif * 255216 jpg * 13780 png * 6677 bmp * 239187 txt,aspx,asp,sql * 208207 xls.doc.ppt * 6063 xml * 6033 htm,html * 4742 js * 8075 xlsx,zip,pptx,mmap,zip * 8297 rar * 01 accdb,mdb * 7790 exe,dll * 5666 psd * 255254 rdp * 10056 bt种子 * 64101 bat * 4059 sgf */ }
但程序运行期间,发现有一种png图片是动图,被加上水印后,图片就不动了(文章效果差)。微信
网上一查原来是一种叫apng格式的图片,弥补了gif图片在显示效果上的不足,但只支持现代浏览器(手机基本都支持)。阿里云
仔细想一想,既然判断前2个字符能够肯定文件类型,那么是否是png格式和apng格式,在文件结构上是有区别的。网上查了下,也验证了个人想法是对的。spa
首先:维基百科上的描述够专业 https://en.wikipedia.org/wiki/APNG (E文很差,软件翻译下).net
其次,CSDN上郭晓东专栏,对PNG格式解释得够清楚了(虽然有些没看懂)翻译
http://blog.csdn.net/hherima/article/details/458470433d
http://blog.csdn.net/hherima/article/details/45848171code
因而照猫画虎找了2个png动图(apng格式),用UltraEdit打开看看
acTL这小样儿躲在这啊,管他什么鬼,第37-40之间的值 ,这应该就是区分png格式和apng格式的关键所在。
修改了一下上面仁兄的代码:
private static string IsAllowedExtension(string filePath) { FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read); BinaryReader reader = new BinaryReader(stream); string fileclass = ""; // byte buffer; try { byte[] head = reader.ReadBytes(41); for (int i = 0; i < 2; i++) { fileclass += head[i].ToString(); } if (fileclass == "13780") { for (int i = 37; i < head.Length; i++) { fileclass += head[i].ToString(); }
if (fileclass != "1378097998476") fileclass = "13780"; } } catch { reader.Dispose(); reader.Close(); } finally { reader.Dispose(); reader.Close(); } return fileclass; /*文件扩展名说明 * 255216 jpg * 208207 doc xls ppt wps * 8075 docx pptx xlsx zip * 5150 txt * 8297 rar * 7790 exe * 3780 pdf * * 4946/104116 txt * 7173 gif * 255216 jpg * 13780 png * 1378097998476 apng * 6677 bmp * 239187 txt,aspx,asp,sql * 208207 xls.doc.ppt * 6063 xml * 6033 htm,html * 4742 js * 8075 xlsx,zip,pptx,mmap,zip * 8297 rar * 01 accdb,mdb * 7790 exe,dll * 5666 psd * 255254 rdp * 10056 bt种子 * 64101 bat * 4059 sgf */ }
最终返回 1378097998476 就是png动图(apng格式,注意扩展名仍是png),而普通png图片为 13780