java 图片类型判断

本文介绍了两种Java中判断图片类型的方案:通过ContentType信息和读取文件流进行16进制分析。同时提到,Webp格式在iOS手机和IE浏览器可能存在显示问题,建议转换为PNG等常见格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:根据图片url中的携带的ContentType信息判断图片的类型,如果图片被强制修改了图片的类型会有问题

/**
 * 根据url中ContentType判断问价格式
 * @param imgUrl
 * @return
 */
public static String getImageType(String imgUrl) {
    BufferedInputStream bis = null;
    HttpURLConnection urlconnection = null;
    String prefix = "";
    try {

        URL url = new URL(imgUrl);
        urlconnection = (HttpURLConnection) url.openConnection();
        urlconnection.connect();
        bis = new BufferedInputStream(urlconnection.getInputStream());
        String imageTypes = HttpURLConnection.guessContentTypeFromStream(bis);
        if (imageTypes.contains("/")) {
            prefix = imageTypes.substring(imageTypes.lastIndexOf("/"));
            prefix = prefix.replaceFirst("/", ".");
            return prefix;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return ".jpg";
}

方法二:将图片的信息读成流转16进制,根据文件流判断文件类型(推荐使用)

public class ImageTypeUtils {
/**
 常用文件的文件头如下:(以前六位为准)
JPEG (jpg),文件头:FFD8FF 
PNG (png),文件头:89504E47 
GIF (gif),文件头:47494638 
TIFF (tif),文件头:49492A00 
Windows Bitmap (bmp),文件头:424D 
CAD (dwg),文件头:41433130 
Adobe Photoshop (psd),文件头:38425053 
Rich Text Format (rtf),文件头:7B5C727466 
XML (xml),文件头:3C3F786D6C 
HTML (html),文件头:68746D6C3E 
Email [thorough only] (eml),文件头:44656C69766572792D646174653A 
Outlook Express (dbx),文件头:CFAD12FEC5FD746F 
Outlook (pst),文件头:2142444E 
MS Word/Excel (xls.or.doc),文件头:D0CF11E0 
MS Access (mdb),文件头:5374616E64617264204A 
WordPerfect (wpd),文件头:FF575043 
Postscript (eps.or.ps),文件头:252150532D41646F6265 
Adobe Acrobat (pdf),文件头:255044462D312E 
Quicken (qdf),文件头:AC9EBD8F 
Windows Password (pwl),文件头:E3828596 
ZIP Archive (zip),文件头:504B0304 
RAR Archive (rar),文件头:52617221 
Wave (wav),文件头:57415645 
AVI (avi),文件头:41564920 
Real Audio (ram),文件头:2E7261FD 
Real Media (rm),文件头:2E524D46 
MPEG (mpg),文件头:000001BA 
MPEG (mpg),文件头:000001B3 
Quicktime (mov),文件头:6D6F6F76 
Windows Media (asf),文件头:3026B2758E66CF11 
MIDI (mid),文件头:4D546864 



    public static final String TYPE_JPG = ".jpg";
    public static final String TYPE_GIF = ".gif";
    public static final String TYPE_PNG = ".png";
    public static final String TYPE_BMP = ".bmp";
    public static final String TYPE_WEBP = ".webp";
    public static final String TYPE_TIF = ".tif";
   // public static final String TYPE_UNKNOWN = "unknown";


    public static void main(String[] args) throws FileNotFoundException {
        File pdfFile = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\F35245_113_P2.jpg");

        //test code
        System.out.println("图片格式1: " + getPicType(new FileInputStream(pdfFile)));

    }
    /**
     * byte数组转换成16进制字符串
     * @param src
     * @return
     */
    public static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * 根据文件流判断图片类型
     * @param fis
     * @return jpg/png/gif/bmp
     */
    public static String getPicType(FileInputStream fis) {
        //读取文件的前几个字节来判断图片格式
        byte[] b = new byte[4];
        try {
            fis.read(b, 0, b.length);
            String type = bytesToHexString(b).toUpperCase();
            if (type.contains("FFD8FF")) {
                return TYPE_JPG;
            } else if (type.contains("89504E47")) {
                return TYPE_PNG;
            } else if (type.contains("47494638")) {
                return TYPE_GIF;
            } else if (type.contains("424D")) {
                return TYPE_BMP;
            }else if(type.contains("52494646")){
                return TYPE_WEBP;
            }else if(type.contains("49492A00")){
                return TYPE_TIF;
            }else{
                return TYPE_JPG;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    /**
     * 根据文件流判断图片类型
     * @param fis
     * @return jpg/png/gif/bmp
     */
    public static String getPicType2(InputStream fis) {
        //读取文件的前几个字节来判断图片格式
        byte[] b = new byte[4];
        try {
            fis.read(b, 0, b.length);
            String type = bytesToHexString(b).toUpperCase();
            if (type.contains("FFD8FF")) {
                return TYPE_JPG;
            } else if (type.contains("89504E47")) {
                return TYPE_PNG;
            } else if (type.contains("47494638")) {
                return TYPE_GIF;
            } else if (type.contains("424D")) {
                return TYPE_BMP;
            }else if(type.contains("52494646")){
                return TYPE_WEBP;
            }else if(type.contains("49492A00")){
                return TYPE_TIF;
            }else{
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}

相关问题:webp图片ios手机和ie浏览器显示会有问题(可转换为png图片)

实例:

url1:原图片路径

path:文件临时存储路径

也可转换为jpg,png等格式

String imgType = ImageTypeUtils.getPicType(new FileInputStream(url1));
if (imgType.equals(".webp")) {//图片转化
    ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();
    WebPReadParam readParam = new WebPReadParam();
    readParam.setBypassFiltering(true);
    reader.setInput(new FileImageInputStream(new File(url)));
    url = path + UUID.randomUUID() + ".png";
    BufferedImage image = reader.read(0, readParam);
    ImageIO.write(image, "png", new File(url));
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值