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];
}
}