JAVA网络图片切割平分并输出流

private static final HostnameVerifier IGNORE_HOSTNAME_VERIFIER = (s, sslSession) -> true;
private static final TrustManager TRUST_MANAGER = new TrustManager();
private static boolean hasBeenInit = false;
/**
 * 处理图片
 * @param url
 * @param x 比例(取值0-1)
 * @param y 比例(取值0-1)
 * @param w 比例(取值0-1)
 * @param h 比例(取值0-1)
 * @param response
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
@GetMapping("/dealImg")
public void dealImg(String url,Double x,Double y,Double w,Double h, HttpServletResponse response) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    if (!hasBeenInit) {
        init();
    }
    URL u = new URL(url);
    HttpsURLConnection urlCon = (HttpsURLConnection) u.openConnection();
    urlCon.setConnectTimeout(6000);
    urlCon.setReadTimeout(6000);
    int code = urlCon.getResponseCode();
    if (code != HttpURLConnection.HTTP_OK) {
        throw new IOException("错误的HTTP响应码:" + code);
    }
    InputStream in = urlCon.getInputStream();
    BufferedImage image = ImageIO.read(in);
    int width = image.getWidth();
    int height = image.getHeight();
    BufferedImage bi = new BufferedImage((int)(width*w), (int)(height*h), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = bi.createGraphics();
    g2.drawImage(image, -(int)(width*x), -(int)(height*y), width, height, null); 
    response.setContentType("image/jpg");
    ImageIO.write(bi, "jpg", response.getOutputStream());
}
/**
 * 忽略ssl证书
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
private static void init() throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
    sslcontext.init(null, new TrustManager[]{TRUST_MANAGER}, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultHostnameVerifier(IGNORE_HOSTNAME_VERIFIER);
    HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
    hasBeenInit = true;
}

private static class TrustManager implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
    }
    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
    }
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值