base64字符串校验是否能生成图片方法

//import org.apache.commons.codec.binary.Base64;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.stereotype.Component;
//import org.springframework.web.multipart.MultipartFile;
//import sun.misc.BASE64Decoder;
//
//import javax.imageio.ImageIO;
//import java.awt.image.BufferedImage;
//import java.io.*;

private boolean isImage(String imgBase64Str) throws Exception {
        if (StringUtil.isEmpty(imgBase64Str)) {
            log.info("图片参数为空");
            return false;
        } else {
            ByteArrayInputStream byteArrayInputStream = null;

            try {
                BASE64Decoder decoder = new BASE64Decoder();
                byte[] byteArray = decoder.decodeBuffer(imgBase64Str);
                byteArrayInputStream = new ByteArrayInputStream(byteArray);
                BufferedImage bufImg = ImageIO.read(byteArrayInputStream);
                if (bufImg == null) {
                    log.info("base64字符串不正确,生成图片失败:str={}", imgBase64Str);
                    return false;
                }
                bufImg = null;
            } finally {
                if (byteArrayInputStream != null) {
                    byteArrayInputStream.close();
                }
            }
        }
        return true;
    }
}

 

你可能感兴趣的:(java)