Imagebase64图片验证码工具类

public class Imagebase64 {
    
    
    static BASE64Encoder encoder = new BASE64Encoder();
    static BASE64Decoder decoder = new BASE64Decoder();


    public static String getImageBinary() {
    
    
        File f = new File("d://in.jpg");
        try {
    
    
            BufferedImage bi = ImageIO.read(f);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", baos);
            byte[] bytes = baos.toByteArray();

            return encoder.encodeBuffer(bytes).trim();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        return null;
    }

    public static String getImage(String path) {
    
    
        File f = new File(path);
        try {
    
    
            BufferedImage bi = ImageIO.read(f);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", baos);
            byte[] bytes = baos.toByteArray();

            return encoder.encodeBuffer(bytes).trim();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        return null;
    }

    public static boolean Base64ToImage(String imgStr,String imgFilePath) {
    
    
        if (StringUtils.isEmpty(imgStr)) // 图像数据为空
            return false;
        try {
    
    
            // Base64解码
            byte[] b = Base64Utils.decodeFromString(imgStr);
            for (int i = 0; i < b.length; ++i) {
    
    
                if (b[i] < 0) {
    
    // 调整异常数据
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
    
    
            return false;
        }

    }

}


猜你喜欢

转载自blog.csdn.net/weixin_45735355/article/details/129118314