java 图片类型判断

Java 专栏收录该内容
16 篇文章 0 订阅

方法一:根据图片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));
}

 

  • 0
    点赞
  • 0
    评论
  • 2
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
package com.ylw.p2p.common.utils; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class FileUtils { public final static Map IMG_FILE_TYPE_MAP = new HashMap(); /** * @Description: 图片文件上传 * @author Xiao.Sky * @creaetime 2015年4月17日下午5:20:27 * @param request * @param response * @param photo * @param strtmp * 文件名称 xxx.jpg * @param path * 文件路径 * @param num * @return */ public static boolean updatePhoto(HttpServletRequest request,HttpServletResponse response, File photo, String strtmp,String path, long num) { File dir = new File(path); // 如果不存在就创建次文件夹 if (!dir.exists()) { dir.mkdirs(); } File newFile = new File(dir, strtmp); // 如果存在此文件就删除此文件 if (newFile.exists()) newFile.delete(); BufferedInputStream bis = null; FileInputStream fis = null; try { fis = new FileInputStream(photo); FileOutputStream fos = new FileOutputStream(newFile); BufferedImage src = ImageIO.read(fis); ImageIO.write(src, "png", fos); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != bis) { bis.close(); } if (null != fis) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } return true; } /** * * @Description: 普通文件上传 * @author Xiao.Sky * @creaetime 2015年4月23
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值