1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- package com.iamberry.wechat.tools;
- import javax.imageio.ImageIO;
- import java.awt.*;
- import java.awt.image.BufferedImage;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.URL;
- import java.net.URLConnection;
- public class DownloadWXCodeUtil {
- /**
- * 下载微信二维码
- * @param urlString
- * @param filename 存储名称
- * @param savePath 路径
- * @param width 宽度
- * @param height 高度
- * @throws Exception
- */
- public static void download(String urlString, String filename,String savePath,int width,int height) throws Exception {
- // 输出的文件流
- File sf=new File(savePath);
- if(!sf.exists()){
- sf.mkdirs();
- }
- // 构造URL
- URL url = new URL(urlString);
- // 打开连接
- URLConnection con = url.openConnection();
- //设置请求超时为5s
- con.setConnectTimeout(5*1000);
- // 输入流
- InputStream is = con.getInputStream();
- BufferedImage bi = ImageIO.read(is);
- ImageIO.write(bi, "png", new File(savePath+filename));
- // JPEGImageDecoder decoderFile = JPEGCodec.createJPEGDecoder(is);
- // BufferedImage image = decoderFile.decodeAsBufferedImage();
- // Image srcImg = image;
- // image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
- // image.getGraphics().drawImage(srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0,0, null);
- // ImageIO.write(image, "JPEG", new File(savePath+filename));
- is.close();
- }
- /**
- * 下载微信二维码
- * @param url
- * @param filename
- * @param savePath
- * @param width
- * @param height
- * @param isCircular 是否为圆
- */
- public static void downloadByNIO2(String url, String filename,String savePath,int width,int height,boolean isCircular) {
- try (InputStream ins = new URL(url).openStream()) {
- BufferedImage bi = ImageIO.read(ins);
- if(isCircular){
- int w = width;
- int h = height;
- BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
- Graphics2D g2 = output.createGraphics();
- output = g2.getDeviceConfiguration().createCompatibleImage(w, h, Transparency.TRANSLUCENT);
- g2.dispose();
- g2 = output.createGraphics();
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- g2.fillRoundRect(0, 0,w, h, 720, 720);
- g2.setComposite(AlphaComposite.SrcIn);
- g2.drawImage(bi, 0, 0, w, h, null);
- g2.dispose();
- ImageIO.write(output, "png", new File(savePath+filename));
- }else{
- Image srcImg = bi;
- bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
- bi.getGraphics().drawImage(srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0,0, null);
- ImageIO.write(bi, "png", new File(savePath+filename));
- }
- ins.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
|