package com.ruoyi.web.util;

import net.sf.jmimemagic.Magic;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.IOException;

/**
 * @ClassName ImageCheck
 * @Description: TODO
 * @Author LX
 * @Date 2023/2/16
 * @Version V1.0
 **/
@Component
public class ImageCheck {
    private MimetypesFileTypeMap mtftp;

    public ImageCheck(){
        mtftp = new MimetypesFileTypeMap();
        /* 不添加下面的类型会造成误判 详见：http://stackoverflow.com/questions/4855627/java-mimetypesfiletypemap-always-returning-application-octet-stream-on-android-e*/
        mtftp.addMimeTypes("image png tif jpg jpeg bmp");
    }
    public  boolean isImage(File file){
        String mimetype= mtftp.getContentType(file);
        String type = mimetype.split("/")[0];
        return type.equals("image");
    }

    public boolean isImage(MultipartFile mf) {
            try {
                String mimeType = Magic.getMagicMatch(mf.getBytes(), false).getMimeType();
                if (mimeType.startsWith("image/")) {
                    return true;
                } else {
                    return false;
                }
            } catch(Exception e) {
                throw new RuntimeException("图片处理异常");
            }
    }
}
