一个非常强大的方法来校验图片的真实性


项目检测时要求对上传到服务器的图片做真实性检验


于是晚上巴拉了一圈设计出一个校验方法


方法单元测试如下:

import static org.junit.Assert.*;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;

import org.devlib.schmidt.imageinfo.ImageInfo;

public class Test {

	@org.junit.Test
	public void testName() throws Exception {
		imgCheck("C:/Users/Administrator/Pictures/Camera Roll/00.png");
	}
	
	public void imgCheck(String filePath){
		RandomAccessFile file = null;
		try {
			file = new RandomAccessFile(filePath, "r");//filePath:文件地址  r:只读
		
			ImageInfo ii = new ImageInfo();
			ii.setInput(file); // in can be InputStream or RandomAccessFile
			ii.setDetermineImageNumber(true); // default is false
			ii.setCollectComments(true); // default is false
			if (!ii.check()) {
			   System.err.println("这不是一张图片");
			   return;
			}else{
				System.err.println("这是一张图片");
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}

用到的包:imageinfo-1.9.jar (最主要最强大的包)



用到的类:RandomAccessFile

这是io包中的一个类,它提供很多方法来操作文件,包括读写支持,与普通的IO流相比,它最大的特别之处就是支持任意访问的方式,程序可以直接跳到任意地方来读写数据。
该类的具体使用方式参考:点击打开链接



你可能感兴趣的:(一个非常强大的方法来校验图片的真实性)