Java 微信小程序imgSecCheck接口示例-校驗一張圖片是否含有違法違規內容


小程序上線后會接到這種警告 

 

ImageUtil代碼

import lombok.extern.slf4j.Slf4j;
 
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.URL;
 
/**
 * @author 小帥丶
 * @className ImageUtil
 * @Description 圖片縮放
 * @Date 2020/9/29-9:58
 **/
@Slf4j
public class ImageUtil {
    /**
     * 縮放比例系數
     */
    private static double SCALING = 0.56;
    /**
     * 符合base64的寬
     */
    private static int MAX_WIDTH = 560;
    /**
     * 最大高
     */
    private static int MAX_HEIGHT = 1000;
 
    /**
     * @Author 小帥丶
     * @Description 根據圖片公網地址轉BufferedImage
     * @Date  2020/9/29 10:52
     * @param url 圖片公網地址
     * @return java.awt.image.BufferedImage
     **/
    public static BufferedImage imgUrlConvertBufferedImage(String url) throws Exception {
        URL urls = new URL(url);
        Image image = Toolkit.getDefaultToolkit().getImage(urls);
        BufferedImage bufferedImage = toBufferedImage(image);
        return bufferedImage;
    }
    /**
     * @Author 小帥丶
     * @Description 根據BufferedImage處理圖片並返回byte[]
     * @Date  2020/9/29 10:55
     * @param bufferedImage
     * @return byte[]
     **/
    public static byte[] zoomImageByte(BufferedImage bufferedImage) throws Exception {
        ByteArrayOutputStream outputStreamZoom = new ByteArrayOutputStream();
        ByteArrayOutputStream outputStreamSource = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "jpg", outputStreamSource);
        BufferedImage bufferedImageZoom = zoomImage(outputStreamSource.toByteArray());
        //寫入縮減后的圖片
        ImageIO.write(bufferedImageZoom, "jpg", outputStreamZoom);
        return outputStreamZoom.toByteArray();
    }
 
    /**
     * @Author 小帥丶
     * @Description 根據byte[]處理圖片並返回byte[]
     * @Date  2020/9/29 10:55
     * @param src
     * @return byte[]
     **/
    public static byte[] zoomImageByte(byte[] src) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        BufferedImage bufferedImage = zoomImage(src);
        //寫入縮減后的圖片
        ImageIO.write(bufferedImage, "jpg", outputStream);
        return outputStream.toByteArray();
    }
 
    /**
     * 圖片縮放 僅適用於微信內容圖片安全檢測使用
     *
     * @param src 為源文件byte
     */
    public static BufferedImage zoomImage(byte[] src) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(src);
        double wr = 0, hr = 0;
        BufferedImage bufferedImage = null;
        //讀取圖片
        BufferedImage bufImg = ImageIO.read(in);
        int height = bufImg.getHeight();
        int width = bufImg.getWidth();
        int cHeight = height;
        int cWidth = width;
        double Scaling = width / height;
        if (Scaling < SCALING) {
            if (height > MAX_HEIGHT) {
                cHeight = MAX_HEIGHT;
                cWidth = (width * MAX_HEIGHT) / height;
            }
            //以寬為縮放比例
        } else {
            if (width > MAX_WIDTH) {
                cWidth = MAX_WIDTH;
                cHeight = (height * MAX_WIDTH) / width;
            }
        }
        //獲取縮放后的寬高
        log.info("寬{},高{}", cWidth, cHeight);
        //設置縮放目標圖片模板
        Image Itemp = bufImg.getScaledInstance(width, cHeight, BufferedImage.SCALE_SMOOTH);
        //獲取縮放比例
        wr = cWidth * 1.0 / width;
        hr = cHeight * 1.0 / height;
        log.info("寬比例{},高比例{}", wr, hr);
        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);
        Itemp = ato.filter(bufImg, null);
        try {
            //寫入縮減后的圖片
            ImageIO.write((BufferedImage) Itemp, "jpg", outputStream);
            ByteArrayInputStream inNew = new ByteArrayInputStream(outputStream.toByteArray());
            bufferedImage = ImageIO.read(inNew);
        } catch (Exception ex) {
            log.info("縮放圖片異常{}", ex.getMessage());
        } finally {
            if (null != outputStream) {
                outputStream.close();
            }
            if (null != in) {
                in.close();
            }
        }
        return bufferedImage;
    }
 
    /**
     * @Author 小帥丶
     * @Description Image轉BufferedImage
     * @Date  2020/9/29 10:47
     * @param image 通過url獲取的image對象
     * @return java.awt.image.BufferedImage
     **/
    public static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage) image;
        }
        // This code ensures that all the pixels in the image are loaded
        image = new ImageIcon(image).getImage();
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment
                .getLocalGraphicsEnvironment();
        try {
            int transparency = Transparency.OPAQUE;
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(image.getWidth(null),
                    image.getHeight(null), transparency);
        } catch (HeadlessException e) {
            // The system does not have a screen
        }
        if (bimage == null) {
            // Create a buffered image using the default color model
            int type = BufferedImage.TYPE_INT_RGB;
            bimage = new BufferedImage(image.getWidth(null),
                    image.getHeight(null), type);
        }
        // Copy image to buffered image
        Graphics g = bimage.createGraphics();
        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return bimage;
    }
}

WeiXinUtil代碼

    private static Integer IMG_WIDTH = 750;
    private static Integer IMG_HEIGHT = 1334;
    /**
     * 圖片檢測接口
     */
    private static String IMG_SEC_URL = "https://api.weixin.qq.com/wxa/img_sec_check?access_token=";
    

/**
     * @Author 
     * @Description 圖片安全檢查
     * @Date  2021.07.02
     * @param imageUrl 圖片公網地址 /適用oss url(referer限制也沒事)/適用oss sts 生成url
     * @param access_token 微信的token
     * @return
     **/
    public  Boolean checkPic(String imageUrl,String access_token) throws Exception{
        BufferedImage bufferedImage = ImageUtil.imgUrlConvertBufferedImage(imageUrl);
        String url = IMG_SEC_URL + access_token;
        //750px * 1334px
        if (bufferedImage.getWidth() > IMG_WIDTH || bufferedImage.getHeight() > IMG_HEIGHT) {
            //縮放圖片
            byte[] newImage = ImageUtil.zoomImageByte(bufferedImage);
        //適合oss鏈接直接傳 不需要file對象 網絡上好多都是file對象 占用帶寬其次慢 String result
= uploadFile(url,newImage); System.out.println(result); System.out.println("general縮放圖片檢測結果 = " + result); JSONObject jso = JSONObject.parseObject(result); String errcode = jso.getString("errcode"); System.out.println("打印errcode"+errcode); if(errcode.equals("87014")){//當content內含有敏感信息,則返回87014 return true; } return false; } else { ByteArrayOutputStream outputStreamSource = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "jpg", outputStreamSource); String result = uploadFile(url,outputStreamSource.toByteArray()); System.out.println(result); System.out.println("general圖片檢測結果 = " + result); JSONObject jso = JSONObject.parseObject(result); String errcode = jso.getString("errcode"); System.out.println("打印errcode"+errcode); if(errcode.equals("87014")){//當content內含有敏感信息,則返回87014 return true; } return false; } }




wxutil 里面兩個方法

 /**
     * 上傳二進制文件
     * @param graphurl 這個地址為微信公眾平台的
     * @param file 圖片文件
     * @return
     */
    public static String uploadFile(String graphurl,MultipartFile file) {
        String line = null;//接口返回的結果
        try {
            // 換行符
            final String newLine = "\r\n";
            final String boundaryPrefix = "--";
            // 定義數據分隔線
            String BOUNDARY = "========7d4a6d158c9";
            // 服務器的域名
            URL url = new URL(graphurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 設置為POST情
            conn.setRequestMethod("POST");
            // 發送POST請求必須設置如下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 設置請求頭參數
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
            conn.setRequestProperty("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
            OutputStream out = new DataOutputStream(conn.getOutputStream());
 
            // 上傳文件
            StringBuilder sb = new StringBuilder();
            sb.append(boundaryPrefix);
            sb.append(BOUNDARY);
            sb.append(newLine);
            // 文件參數,photo參數名可以隨意修改
            sb.append("Content-Disposition: form-data;name=\"image\";filename=\""
                    + "https://api.weixin.qq.com" + "\"" + newLine);
            sb.append("Content-Type:application/octet-stream");
            // 參數頭設置完以后需要兩個換行,然后才是參數內容
            sb.append(newLine);
            sb.append(newLine);
 
            // 將參數頭的數據寫入到輸出流中
            out.write(sb.toString().getBytes());
 
            // 讀取文件數據
            out.write(file.getBytes());
            // 最后添加換行
            out.write(newLine.getBytes());
 
            // 定義最后數據分隔線,即--加上BOUNDARY再加上--。
            byte[] end_data = (newLine + boundaryPrefix + BOUNDARY
                    + boundaryPrefix + newLine).getBytes();
            // 寫上結尾標識
            out.write(end_data);
            out.flush();
            out.close();
            // 定義BufferedReader輸入流來讀取URL的響應
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            while ((line = reader.readLine()) != null) {
                return line;
            }
        } catch (Exception e) {
            System.out.println("發送POST請求出現異常!" + e);
        }
        return line;
    }
 
    /**
     * 上傳二進制文件
     * @param apiurl 公眾平台接口地址
     * @param file 圖片文件
     * @return
     */
    public static String uploadFile(String apiurl, byte[] file) {
        //接口返回的結果
        String line = null;
        try {
            // 換行符
            final String newLine = "\r\n";
            final String boundaryPrefix = "--";
            // 定義數據分隔線
            String BOUNDARY = "========7d4a6d158c9";
            // 服務器的域名
            URL url = new URL(apiurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 設置為POST情
            conn.setRequestMethod("POST");
            // 發送POST請求必須設置如下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 設置請求頭參數
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
            conn.setRequestProperty("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 14_0_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.15(0x17000f31) NetType/WIFI Language/zh_CN");
            OutputStream out = new DataOutputStream(conn.getOutputStream());
 
            // 上傳文件
            StringBuilder sb = new StringBuilder();
            sb.append(boundaryPrefix);
            sb.append(BOUNDARY);
            sb.append(newLine);
            // 文件參數,photo參數名可以隨意修改
            sb.append("Content-Disposition: form-data;name=\"image\";filename=\""
                    + "https://api.weixin.qq.com" + "\"" + newLine);
            sb.append("Content-Type:application/octet-stream");
            // 參數頭設置完以后需要兩個換行,然后才是參數內容
            sb.append(newLine);
            sb.append(newLine);
 
            // 將參數頭的數據寫入到輸出流中
            out.write(sb.toString().getBytes());
 
            // 讀取文件數據
            out.write(file);
            // 最后添加換行
            out.write(newLine.getBytes());
 
            // 定義最后數據分隔線,即--加上BOUNDARY再加上--。
            byte[] end_data = (newLine + boundaryPrefix + BOUNDARY
                    + boundaryPrefix + newLine).getBytes();
            // 寫上結尾標識
            out.write(end_data);
            out.flush();
            out.close();
            // 定義BufferedReader輸入流來讀取URL的響應
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            while ((line = reader.readLine()) != null) {
                return line;
            }
        } catch (Exception e) {
            System.out.println("發送POST請求出現異常!" + e);
        }
        return line;
    }

 

 

最后自己 在控制層 直接傳入文本或圖片 返回true代表有違規圖片或者文字 給出自己業務提示語 例如:您的圖片或文字包含敏感信息不合法

 

 

nohup  java -jar xxx.jar >/dev/null 2>&1 &


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM