善忘技术夹 Logo
善忘技术夹
技术文章 · 4440 阅读

微信公众号开发--善忘影视(十)

优化列表加载速度,列表图片压缩

如下图左边的图片 列表显示页

运行了一段时间后,发现打开公众号,或者网页的列表速度很慢,用chrome查看了一下加载时间, 主要是还是在加载图片上,毕竟列表加载那么大的图片,是一件很费时间的事情,现在我就来优化它。

主要分三个步骤 1. 获取列表图片(获取详情页中的海报图片) 2. 压缩图片 3. 上传云存储图片,保存路径到数据库中 3. 修改显示列表图片,显示压缩后的图片

获取列表图片

主要是通过定时器来获取列表数据,然后分析详情页的里面的图片地址,下载对应图片。 关键代码如下

List<MovieCrawl> movieCrawlList =  movieCrawlMapper.listNotDealImgByCreateTime();
        try {
            movieCrawlList.forEach(mc -> {
                String content = mc.getContent();
                if (StringUtils.isNotNull(content)) {
                    Document doc = Jsoup.parse(content);
                    Elements imgs = doc.select("img");
                    StringBuffer stringBuffer = new StringBuffer();
                    mc.setSmallPic("img/logo.jpg");
                    if (imgs.size() > 0) {
                        Iterator<Element> it = imgs.iterator();
                        String src = it.next().attr("src");
                        //mc.setFirstImg(src);
                        String smallPic = downloadFileResizeImg(src);
                        if (StringUtils.isNotNull(smallPic)) {
                            String ext = FileUtil.getExt(new File(smallPic).getName());
                            String key = UploadUtils.generateFilename("img/small", ext);
                            try {
                                uploadQiNiu.upload(smallPic,key);
                                mc.setSmallPic(key);
                            } catch (IOException e) {
                                logger.error(e.getMessage(), e);
                            }
                        }
                    }
                }
                movieCrawlMapper.updateByPrimaryKeySelective(mc);
            });
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

压缩图片

上面代码中String smallPic = downloadFileResizeImg(src); 就是表示下载图片 代码如下,里面还有压缩图片的代码

    
    
            filename = uuid + "_" + filename;
            System.out.print(filename);
    
            String downloadpath = ResourceBundleUtils.getAppAbstractPath();
            File t_file = new File(downloadpath + filename);
    
            OutputStream os = new FileOutputStream(t_file);
            int tmp = 0;
            while ((tmp = is.read()) != -1) {
                os.write(tmp);
            }
            os.close();
            is.close();
    
    
            String ext = FileUtil.getExt(filename);
            File deskFile = new File(downloadpath + uuid + "_180_180." + ext);
    
    
            isi.resizeFix(t_file, deskFile, 180, 180);
    
            return deskFile.getAbsolutePath();
    
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return null;
    }```
    

压缩图片代码`isi.resizeFix(t_file, deskFile, 180, 180);`
    
    
    public static void resizeFix(File srcFile, File destFile, int boxWidth,
                int boxHeight) throws IOException, MagickException {
            ImageInfo info = new ImageInfo(srcFile.getAbsolutePath());
            MagickImage image = new MagickImage(info);
            // 计算缩小宽高
            Dimension dim = image.getDimension();
            int width = (int) dim.getWidth();
            int height = (int) dim.getHeight();
            int zoomWidth;
            int zoomHeight;
            if ((float) width / height > (float) boxWidth / boxHeight) {
                zoomWidth = boxWidth;
                zoomHeight = Math.round((float) boxWidth * height / width);
            } else {
                zoomWidth = Math.round((float) boxHeight * width / height);
                zoomHeight = boxHeight;
            }
            // 缩小
            MagickImage scaled = image.scaleImage(zoomWidth, zoomHeight);
            // 输出
            scaled.setFileName(destFile.getAbsolutePath());
            scaled.writeImage(info);
            scaled.destroyImages();
        }
        ```
    
    ####上传图片到云存储
    我这里用的是七牛, 以前用的是阿里云的oss,现在不免费了,就先用用有一定免费额度的七牛了。都是有线程的api可以调用,不过七牛里面设置区域比较坑,在调用上传的时候记得加上这句。```Config.zone = Zone.zone1();```
    不然总是返回然后设置zone的问题。
    
    

public void upload(String filePath, String key) throws IOException { try { Config.zone = Zone.zone1(); //调用put方法上传 Response res = uploadManager.put(filePath, key, getUpToken()); //打印返回的信息 System.out.println(res.toString()); } catch (QiniuException e) { Response r = e.response; // 请求失败时打印的异常的信息 System.out.println(r.toString()); try { //响应的文本信息 System.out.println(r.bodyString()); } catch (QiniuException e1) { //ignore } } } ```

#### 最后修改对应显示的列表

`<img class="weui_media_appmsg_thumb" src="/upload/${item.firstImg}" alt="">`