图片文件合法性校验

来源:互联网 发布:网络运营工作计划 编辑:程序博客网 时间:2024/04/29 19:03
 
/**
     * 效验图片文件是否合法,包括后缀名、大小和尺寸
     *
     * @author Tony Lin Added on 2008-11-18
     * @param  fileEntity
     * @throws FileSafetyException
     */
    public static void fileSafetyCheck(FileEntity fileEntity) throws FileSafetyException {
     final String[] FILETYPES = new String[]{  
            ".jpg", ".bmp", ".jpeg", ".png", ".gif",
            ".JPG", ".BMP", ".JPEG", ".PNG", ".GIF"
        };
     final int MINLENGTH = 1;
        final int MAXLENGTH = 2097152; //2兆
        final int WIDTH = 168;
        final int HEIGHT = 120;
        
        if (fileEntity == null)
         throw new FileSafetyException("Sorry, fileEntity can't be null.");
        String filename = fileEntity.getFileName();
        //图片类型效验
        boolean flag = false;
        for (int i = 0; i < FILETYPES.length; i++) {
            String fileType = FILETYPES[i];
            if (filename.endsWith(fileType)) {
                flag = true;
                break;
            }
        }
        if (!flag) throw new FileSafetyException("Illegal file types.");
        //文件长度效验
        byte[] fileContent = fileEntity.getFileContent();
        int len = fileContent.length;
        if (len < MINLENGTH || len > MAXLENGTH)
         throw new FileSafetyException("Sorry, fileContent length invalid.");
        //图片尺寸检查
        BufferedImage image = null;
        int width = 0;
        int height = 0;
        ImageInputStream imageInputStream = null;
        try {
            imageInputStream = ImageIO.createImageInputStream(new ByteArrayInputStream(fileContent));
            image = ImageIO.read(imageInputStream);
            width = image.getWidth();
            height = image.getHeight();
        } catch (IOException e) {
            throw new FileSafetyException(e.getMessage());
        } finally {
            image = null;
        }
        if (width != WIDTH || height != HEIGHT)
            throw new FileSafetyException("Photo size illegal.");
    }
    /**
     * 将一个File对象封装成FileEntity对象,以实现网络传输
     *
     * @author Tony Lin Added on 2008-11-18
     * @param  file
     * @return FileEntity
     * @throws IOException
     */
    public static FileEntity getFileEntity(File file) throws IOException {
        int length = (int) file.length(); //得到文件的长度
        String filename = file.getName().trim();
        byte[] fileContent = new byte[length];
        BufferedInputStream inStreaam = null;
        try {
            inStreaam = new BufferedInputStream(new FileInputStream(file));
            inStreaam.read(fileContent, 0, fileContent.length);
        } catch (IOException e) {
            throw new IOException(e.getMessage());
        } finally {
            inStreaam.close();
        }
        FileEntity fileEntity = new FileEntity(filename, fileContent);
        return fileEntity;
    }
原创粉丝点击