正文

Java 判断文件是否为图片文件GIF,PNG,JPG2009-10-15 00:40:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/txdnet/49272.html

分享到:

首先大家需要了解的是Java里判断Image文件信息格式(GIF/PNG/JPG)/Size/Height/Width的原理: 1,判断Image格式用UE打开GIF/PNG/JPG格式的图片文件我们会发现在文件头部某几个位置的字节的值连起来是'GIF'/'PNG'/'JFIF'它们的位置分别如下:GIF: 012JFIF(JPG): 6789PNG: 123这样我们可以通过判断这几个字节值来得到Image文件格式: String type = "";byte b0 = image.getFileData()[0];byte b1 = image.getFileData()[1];byte b2 = image.getFileData()[2];byte b3 = image.getFileData()[3];byte b6 = image.getFileData()[6];byte b7 = image.getFileData()[7];byte b8 = image.getFileData()[8];byte b9 = image.getFileData()[9];// GIFif (b0 == (byte) 'G' && b1 == (byte) 'I' && b2 == (byte) 'F')type = "GIF";// PNGelse if (b1 == (byte) 'P' && b2 == (byte) 'N' && b3 == (byte) 'G')type = "PNG";// JPGelse if (b6 == (byte) 'J' && b7 == (byte) 'F' && b8 == (byte) 'I' && b9 == (byte) 'F')type = "JPG";elsetype = "Unknown";image.setType(type);2,判断Image大小FileImageInputStream fiis = new FileImageInputStream(new File(image.getPath()));image.setSize((float) fii.length() / 1000 + "KB");3,判断Image宽度和高度ImageIcon ii = new ImageIcon(image.getPath());image.setHeight(String.valueOf(ii.getIconHeight()));image.setWidth(String.valueOf(ii.getIconWidth())); 下面是判断文件是否为图片文件的一个JAVA程序 import java.io.*;public class isImg{public static void main(String[] args){if (!isImage("d://1.txt")){ System.out.println("不是图片");}else{System.out.println("是图片");}}/*** 判断文件是否为图片文件(GIF,PNG,JPG)* @param srcFileName* @return*/public static boolean isImage(String srcFileName) {FileInputStream imgFile = null;byte[] b = new byte[10];int l = -1;try {imgFile = new FileInputStream(srcFileName);l = imgFile.read(b);imgFile.close();} catch (Exception e) {return false;}if (l == 10) {byte b0 = b[0];byte b1 = b[1];byte b2 = b[2];byte b3 = b[3];byte b6 = b[6];byte b7 = b[7];byte b8 = b[8];byte b9 = b[9];if (b0 == (byte) 'G' && b1 == (byte) 'I' && b2 == (byte) 'F') {return true;} else if (b1 == (byte) 'P' && b2 == (byte) 'N' && b3 == (byte) 'G') {return true;} else if (b6 == (byte) 'J' && b7 == (byte) 'F' && b8 == (byte) 'I'&& b9 == (byte) 'F') {return true;} else {return false;}} else {return false;}}} 应用: 检测客户端是否上传了合法的图片文件,防止恶意修改扩展名上传文件 -- 更多文章笔记:http://www.txdnet.cn/rss/2.xml

阅读(9425) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册