java 实现BufferedImage和ImageReader两种方式获取图片宽高、判断图片类型、获取图片大小工具类代码以及测试响应结果

开发经验 专栏收录该内容
16 篇文章 0 订阅

源码:

import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class ImageUtil {


    public static void checkImageIsNormal(final MultipartFile imageFile)
            throws Exception {
        if (imageFile == null) {
            throw new IllegalArgumentException("imageFile == null");
        }
        final long imageSize = imageFile.getSize();
        System.out.println("length:" + imageSize);
        if (imageSize > Config.IMG_MAX_SIZE) {
            throw new IllegalArgumentException("图片大小不能超过2M");
        }
        final String fileName = imageFile.getOriginalFilename();
        final String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        System.out.println("name:" + fileName);
        System.out.println("type:" + suffix);
        final String[] imageTypes = { "jpeg", "jpg", "png", "bmp" };
        final List<String> imageTypeList = Arrays.asList(imageTypes);
        if (!imageTypeList.contains(suffix.toLowerCase())) {
            throw new IllegalArgumentException("图片格式不支持");
        }
        final BufferedImage bufferedImage = ImageIO.read(imageFile
                .getInputStream());
        final int width = bufferedImage.getWidth();
        final int height = bufferedImage.getHeight();
        System.out.println("width:" + width + " height:" + height);
        if (width < Config.IMG_MIN_PIXEL || width > Config.IMG_MAX_PIXEL
                || height < Config.IMG_MIN_PIXEL
                || height > Config.IMG_MAX_PIXEL) {


            throw new IllegalArgumentException("图片尺寸不符合");
        }
    }


    public static void checkImageIsNormal(final String imageUrl)
            throws Exception {
        if (imageUrl == null) {
            throw new IllegalArgumentException("imageUrl == null");
        }
        final URL url = new URL(imageUrl);
        final URLConnection uc = url.openConnection();


        if (uc == null) {
            throw new NullPointerException("网络图片不存在");
        }
        final long imageSize = uc.getContentLength();
        System.out.println("netImage length:" + imageSize);
        if (imageSize > Config.IMG_MAX_SIZE) {
            throw new IllegalArgumentException("图片大小不能超过2M");
        }


        final ImageInputStream iis = ImageIO.createImageInputStream(uc
                .getInputStream());


        final Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
        if (!iter.hasNext()) {
            throw new RuntimeException("No readers found!");
        }
        final ImageReader reader = iter.next();
        System.out.println("Net imageType: " + reader.getFormatName());
        final String suffix = reader.getFormatName();
        final String[] imageTypes = { "jpeg", "jpg", "png", "bmp" };
        final List<String> imageTypeList = Arrays.asList(imageTypes);
        if (!imageTypeList.contains(suffix.toLowerCase())) {
            throw new IllegalArgumentException("图片格式不支持");
        }


        reader.setInput(iis, true);
        final int width = reader.getWidth(0);
        final int height = reader.getHeight(0);
        System.out.println("width:" + width + " height:" + height);
        if (width < Config.IMG_MIN_PIXEL || width > Config.IMG_MAX_PIXEL
                || height < Config.IMG_MIN_PIXEL
                || height > Config.IMG_MAX_PIXEL) {


            throw new IllegalArgumentException("图片尺寸不符合");
        }
    }


    public static void imageReader() throws Exception, IOException {
        final long start = System.currentTimeMillis();
        final File file = new File("wwj6.jpg");
        final ImageInputStream iis = ImageIO
                .createImageInputStream(new FileInputStream(file));


        final Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
        if (!iter.hasNext()) {
            throw new RuntimeException("No readers found!");
        }
        final ImageReader reader = iter.next();
        reader.setInput(iis, true);
        final int width = reader.getWidth(0);
        final int height = reader.getHeight(0);
        final long end = System.currentTimeMillis();
        System.out.println("userd:" + (end - start) + "ms");
        System.out.println("width:" + width + " height:" + height);
    }


    public static void bufferedImage() throws Exception, IOException {
        final long start = System.currentTimeMillis();
        final File file = new File("wwj6.jpg");
        final BufferedImage bufferedImage = ImageIO.read(new FileInputStream(
                file));
        final int width = bufferedImage.getWidth();
        final int height = bufferedImage.getHeight();
        final long end = System.currentTimeMillis();
        System.out.println("userd:" + (end - start) + "ms");
        System.out.println("width:" + width + " height:" + height);
    }


    public static void main(final String[] args)  {


        System.out.println("imageReader:");
        try {
            imageReader();
        } catch (final Exception e) {
            e.printStackTrace();
        }
        System.out.println("bufferedImage:");
        try {
            bufferedImage();
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

}

 

 

 

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

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
©️2021 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值