调用图片压缩接口

delu

接口

http://baidu.com

活动页

https://wx.tuhu.cn/staticpage/promotion/activity/?id=3453D23C&id=3453D23C#!/page=home

添加依赖

<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.10.2</version>
        </dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.2</version>
        </dependency>

爬取活动页的所有图片

package com.example.demo.crawler;
 
 
 import jdk.nashorn.internal.ir.ContinueNode;

 import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.net.URL;
 import java.net.URLConnection;
 import java.util.*;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
 public class Util {
     
     // 地址
     private static final String URL = "https://item.tuhu.cn/promotion/activity/3453D23C.html";
     // 获取img标签正则
     private static final String IMGURL_REG = "<img.*src=(.*?)[^>]*?>";
     // 获取src路径的正则
     private static final String IMGSRC_REG = "[a-zA-Z]+://[^\\s]*";
     // 获取html内容
     public static String getHTML(String srcUrl) throws Exception {
         URL url = new URL(srcUrl);
         URLConnection conn = url.openConnection();
         InputStream is = conn.getInputStream();
         InputStreamReader isr = new InputStreamReader(is);
         BufferedReader br = new BufferedReader(isr);
         String line = null;
         StringBuffer buffer = new StringBuffer();
         while ((line = br.readLine()) != null) {
             buffer.append(line);
             buffer.append("\n");
         }
         br.close();
         isr.close();
         is.close();
         return buffer.toString();
     }
     // 获取image url地址
     public static List<String> getImageURL(String html) {
         Matcher matcher = Pattern.compile(IMGURL_REG).matcher(html);
         List<String> list = new ArrayList<>();
         while (matcher.find()) {
             list.add(matcher.group());
         }
         return list;
         }
         
         
         
     // 获取image src地址
     public static List<String> getImageSrc(List<String> listUrl) {
         List<String> listSrc = new ArrayList<String>();
         for (String img : listUrl) {
             Matcher matcher = Pattern.compile(IMGSRC_REG).matcher(img);
             while (matcher.find()) {
                 
                 listSrc.add(matcher.group().substring(0,
                         matcher.group().length() - 1));
             }
         }
         return listSrc;
     }
    
     // 下载图片
     private static void Download(List<String> listImgSrc) {
         try {
             // 开始时间
             Date begindate = new Date();
             int count=0;
             for (String url : listImgSrc) {
                 
                 // 开始时间
                 Date begindate2 = new Date();
                 String imageName = url.substring(url.lastIndexOf("/") + 1,
                         url.length());
                 
                 URL uri = new URL(url);
                 InputStream in = uri.openStream();
                 FileOutputStream fo = new FileOutputStream(new File(imageName));// 文件输出流
                 byte[] buf = new byte[1024];
                 int length = 0;
                 System.out.println("开始下载:" + url);
                 while ((length = in.read(buf, 0, buf.length)) != -1) {
                     fo.write(buf, 0, length);
                 }
                 // 关闭流
                 in.close();
                 fo.close();
                 System.out.print(imageName + "下载完成");
                 count++;
                 System.out.println(count);
                 // 结束时间
                 Date overdate2 = new Date();
                 double time = overdate2.getTime() - begindate2.getTime();
                 System.out.println("耗时:" + time / 1000 + "s");
             }
            
             
             Date overdate = new Date();
             double time = overdate.getTime() - begindate.getTime();
             System.out.println("总耗时:" + time / 1000 + "s");
             
         } catch (Exception e) {
             System.out.println("下载失败");
             e.printStackTrace();
         }
     }
     
     public static List<String> getTrueURL(List<String> listUrl){
         List<String> list = new ArrayList<>();
         //去掉url后多出的双引号
         for (String s:listUrl){
             String regexp = "\"";
             s = s.replaceAll(regexp, "");
             list.add(s);
             System.out.println(s);
         }
         //去掉一个html的url
         list.remove(48);
         return list;
     }
     
     public static void main(String[] args) throws Exception {
        
         String html = getHTML(URL);
         List<String> listUrl = getImageURL(html);
         List<String> listSrc = getImageSrc(listUrl);
         List<String> list = getTrueURL(listSrc);
       
         Download(list);
         
         //System.out.println("所有图片的大小:"+Length.getNetWorkFile(list));
     }
 }

将图片保存在“D:\images\hello”中

遍历图片调用接口

 package com.example.demo.crawler;

 import org.apache.http.HttpEntity;
 import org.apache.http.client.ClientProtocolException;
 import org.apache.http.client.methods.CloseableHttpResponse;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.entity.mime.MultipartEntityBuilder;
 import org.apache.http.entity.mime.content.FileBody;
 import org.apache.http.impl.client.CloseableHttpClient;
 import org.apache.http.impl.client.HttpClients;

 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.List;


 public class Httphost {
    
     public void start(List<File> fileList) throws ClientProtocolException, IOException{
         
    
         try{
             
             for (File f:fileList){
                 FileBody imageFileBody = new FileBody(f);
                 System.out.println("装载数据完成");
                 //将所有需要上传元素打包成HttpEntity对象
                 HttpEntity reqEntity = MultipartEntityBuilder.create()
                         .addPart("image",imageFileBody).build();
                        
                 System.out.println("打包数据完成");
                 //创建HttpPost对象,用于包含信息发送post消息
                 HttpPost httpPost = new HttpPost("http://compression.koala.works/compression");
                 httpPost.setEntity(reqEntity);
                 System.out.println("创建post请求并装载好打包数据");
                 //创建HttpClient对象,传入httpPost执行发送网络请求的动作
                 CloseableHttpClient httpClient = HttpClients.createDefault();
                 CloseableHttpResponse response = httpClient.execute(httpPost);
                 System.out.println("发送post请求并获取结果");
                 //获取返回的实体内容对象并解析内容
                 HttpEntity resultEntity = response.getEntity();
                 String responseMessage = "";
    
                 System.out.println("开始解析结果");
                 if(resultEntity!=null){
                     
                     String imageName = f.getName();
                     InputStream is = resultEntity.getContent();
                     //文件输出流
                     FileOutputStream fo = new FileOutputStream(new File("D:\\途虎养车\\压缩后的图片\\"+imageName));
                     byte[] buf = new byte[1024];
                     int length = 0;
        
                     while ((length = is.read(buf, 0, buf.length)) != -1) {
                         fo.write(buf, 0, length);
                     }
    
                     System.out.println(imageName+"图片输出完成。");
                     is.close();
                     fo.close();
                 }
             
         }
         
         
             
         }catch (Exception e){
            e.printStackTrace(); 
         }
     }
    
     public static void main(String[] args) throws ClientProtocolException, IOException {
         List<File> list = GetAllPicturesPath.getPath();
         Httphost ht = new Httphost();
         ht.start(list);
     }
 }

图片经过压缩后保存在“D:\途虎养车\压缩后的图片”

遍历图片得出压缩比

package com.example.demo.crawler;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

public class GetAllPicturesPath {
    
    public static List<File> getPath(){
        
        String path = "D:\\images\\hello";
        File file = new File(path);
        //遍历path下的文件和目录,放在File数组中
        File[] fs = file.listFiles();
        System.out.println();
        List<File> list = new ArrayList<>();
        for(File f:fs){
            //若非目录(即文件),则打印
            
            if(!f.isDirectory())
            {
                list.add(f);
                //System.out.println(f);
            }
        }
        return list;
    }
    
    public static int getLength(String path){
        //String path = "D:\\images\\hello";
        File file = new File(path);
        //遍历path下的文件和目录,放在File数组中
        File[] fs = file.listFiles();
        int count = 0;
        int num = 0;
        try{
            for(File f:fs){
            //若非目录(即文件),则打印
            if(!f.isDirectory())
            {
                FileInputStream fileInputStream = new FileInputStream(f);
                System.out.println(f);
                System.out.println("文件大小:"+String.valueOf(fileInputStream.available()));
                int length = fileInputStream.available();
                count+=length;
                num++;
                
            }
        }   
           
            System.out.println("图片总大小:"+count);
            System.out.println("图片数量"+num);
            
        }catch (Exception e){
            e.printStackTrace();
        }
        return count;
    }
    
    
    
    
    
    public static void main(String[] args) { 
        
        /*List<File> list = getPath();
        for (File f:list){
            System.out.println(f);
        }*/
        
        int countBefore = getLength("D:\\images\\hello");
        int countAfter = getLength("D:\\途虎养车\\压缩后的图片");
        float compress = (float)countBefore/countAfter;
        System.out.println("压缩比为:"+compress);
        
        
    }
}

1536804290133

得到压缩比为:2.2069361

坚持原创技术分享,您的支持将鼓励我继续创作!