Java reads network pictures, stores them locally and generates thumbnails

Previously, python crawler was used to capture movie website information as the data source of its own website. The pictures contained in it are all network pictures. There will be such a problem:

When the access speed of the original website is relatively slow, the website image loading time will also become very slow, and if the original website hangs, the images will not be directly accessed.

At this time, the user experience is very bad, so it is optimized:

Each time the backend is started, the task will be started by default. First, store the unconverted network pictures locally, and then change the picture list in the web page to access the local pictures. This solves the problem of slow loading and reduces the coupling with the original website. The specific steps are as follows:

1. Create a folder for saving pictures

My save path: F: \ images

2. Create a new createlocalimage class for image conversion

package com.cn.beauty.task;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class createLocalImage {
	// 需要保存到本地的根路径
    private static String basePath = "F:/";

    public static void main(String[] args) {
    	// 网页图片路径
        String destUrl = "http://5b0988e595225.cdn.sohucs.com/images/20200215/349bb3cb88b744dcb67f37dba2f71abf.jpeg";
        String filePath = createLocalImageMethod(destUrl);
        System.out.println("生成的相对文件路径为" + filePath);
    }

    private static String createLocalImageMethod(String destUrl) {
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        HttpURLConnection httpUrl = null;
        URL url = null;
        int BUFFER_SIZE = 1024;
        byte[] buf = new byte[BUFFER_SIZE];
        int size = 0;
        String filePath = "";
        try {
            System.out.println("原始图片URL为:" + destUrl);
            String[] fileNameArray = destUrl.split("\\/");
            if (fileNameArray.length > 1) {
                String fileName = fileNameArray[fileNameArray.length - 1];
                filePath = "images/" + fileName;
                File file = new File(basePath + filePath);
                if (!file.exists()) {
                    url = new URL(destUrl);
                    httpUrl = (HttpURLConnection) url.openConnection();
                    httpUrl.connect();
                    bis = new BufferedInputStream(httpUrl.getInputStream());
                    fos = new FileOutputStream(basePath + filePath);
                    while ((size = bis.read(buf)) != -1) {
                        fos.write(buf, 0, size);
                    }
                    fos.flush();
                }
                // 后续对图片进行缩略图处理,见后面代码
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassCastException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
                bis.close();
                httpUrl.disconnect();
            } catch (IOException e) {
            } catch (NullPointerException e) {
            }
        }
        return filePath;
    }
}

After running, it is found that the picture has been successfully generated:

If it is the display of the picture list, the original picture is too large, which will still affect the loading speed. At this time, we can process the picture as a thumbnail for display.

We use a powerful image processing tool class: thumbnails, which supports the following functions:

The requirements here are relatively simple, and only the function of scaling according to the specified size is used.

Import the corresponding jar package:

<dependency>
      <groupId>net.coobird</groupId>
      <artifactId>thumbnailator</artifactId>
      <version>0.4.8</version>
</dependency>

Add the code implementation of thumbnail generation in createlocalimage method:

	String thumbName = fileName.split("\\.")[0] + "_thumb." + fileName.split("\\.")[1];
    String thumbPath = basePath + filePath.replace(fileName, thumbName);
    //将要转换出的小图文件
    File fo = new File(thumbPath);
    if (fo.exists()) {
         return thumbPath;
    }
    // 第一个参数是原始图片的路径,第二个是缩略图的路径
    Thumbnails.of(basePath + filePath).size(120, 120).toFile(thumbPath);
    System.out.println("生成的缩略图路径为:" + thumbPath);

Run again and find that the thumbnail has been successfully generated:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>