Java图片处理的坑:披着羊皮的狼,图片格式不能只根据后缀判断

           最近在做图片处理时,写的图片处理simpleImageTool小库,在应用时发现有的图片后缀名是不对应的,比如实际文件是gif,文件名却是png。导致处理异常,为了避免出现这种情况,就需要对文件流进行文件类型判断。我是对文件开头的标识来判断才得以解决。

          

    protected static int read(InputStream in) {
        int curByte = 0;
        try {
            curByte = in.read();
        } catch (IOException e) {
          //  status = STATUS_FORMAT_ERROR;
        }
        return curByte;
    }
    public static   boolean isGif(BufferedInputStream in){
        String type = "";
        in.mark(6);
        for (int i = 0; i < 6; i++) {
            type += (char) read(in);
        }
        try {
            in.reset();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  type.startsWith("GIF");
    }

        对InputStream的流必须在包一层BufferedInputStream 才具备mark标记和reset功能,否则对inputStrean做了类型判断,第二次读取进行图片处理会出错,根据源码跟踪发现InputStream

 

 

    public synchronized void mark(int readlimit) {}

        没干事。

 

       BufferedInputStream中进行了实现:

 

    public synchronized void mark(int readlimit) {
        marklimit = readlimit;
        markpos = pos;
    }

       最终包一层就得以解决第二次读取问题。
 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值