时间:2017年07月15日星期六
说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com
教学源码:无
学习源码:https://github.com/zccodere/s...

第一章:课程介绍

1-1 课程介绍

在用户进行信息概略浏览的时候,提供缩略图

提升程序性能
提升程序效率

课程内容

Java图片等比缩略图实现方式介绍
课程项目案例介绍
实现图片等比缩略图的生成

1-2 实现方式

实现方式

Thumbnailator类库:
    推荐使用
    size()API方法
Java AWT类库:
    根据缩略比例计算缩略图高度和宽度
    使用Image类获得原图的缩放版本
    使用ImageIO类保存缩略图
    BufferedImage类
    ImageIO类
    Graphics类

第二章:案例介绍

2-1 案例介绍

案例介绍

基于springmvc框架的Java Web应用程序,允许上传图片,并生成图片的缩略图

效果示意图

clipboard.png

clipboard.png

第三章:案例实现

3-1 框架搭建

个人学习时,使用springboot+freemaker+mavem搭建,POM文件如下

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.myimooc</groupId>
    <artifactId>thumbnail</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>thumbnail</name>
    <url>http://maven.apache.org</url>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

项目层级结构如下

clipboard.png

3-2 上传页面开发

代码演示:

<html>
<head>
<title>上传文件</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>

    <h2>图片上传</h2>
    
    <form action="thumbnail" enctype="multipart/form-data" method="post">
        <h2>请上传图片</h2>
        <input type="file" name="image" id="image"/>
        <input type="submit" value="上传" />
    </form>
    
</body>
</html>

3-3 控制器开发

代码演示:

package com.myimooc.thumbnail.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.myimooc.thumbnail.service.ThumbnailService;
import com.myimooc.thumbnail.service.UploadService;

/**
 * Thumbnail 控制器类
 * @author ZhangCheng on 2017-07-19
 *
 */
@Controller
@RequestMapping("/")
public class ThumbnailController {
    
    private static Logger logger = LoggerFactory.getLogger(ThumbnailController.class);
    
    @Autowired
    private UploadService uploadService;
    @Autowired
    private ThumbnailService thumbnailService;
    
    @PostMapping("thumbnail")
    public ModelAndView thumbnail(MultipartFile image,HttpServletRequest request){
        
        ModelAndView mav = new ModelAndView();
        
        String uploadPath = "static/images/";
        String realUploadPath = getClass().getClassLoader().getResource(uploadPath).getPath();
        
        logger.info("上传相对目录:{}",uploadPath);
        logger.info("上传绝对目录:{}",uploadPath);
        
        String imageUrl = uploadService.uploadImage(image, uploadPath, realUploadPath);
        String thumImageUrl = thumbnailService.thumbnail(image, uploadPath, realUploadPath);
        
        mav.addObject("imageURL", imageUrl);
        mav.addObject("thumImageUrl", thumImageUrl);
        mav.setViewName("thumbnail");
        return mav;
    }
    
}

3-4 图片上传服务类开发

代码演示:

package com.myimooc.thumbnail.service;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 图片上传服务类
 * @author ZhangCheng on 2017-07-19
 *
 */
@Service
public class UploadService {
    
    private static Logger logger = LoggerFactory.getLogger(UploadService.class);
    
    public String uploadImage(MultipartFile file,String uploadPath,String realUploadPath){
        
        logger.info("上传的相对路径:{}",uploadPath);
        logger.info("上传的绝对路径:{}",realUploadPath);
        
        String filePath = realUploadPath + file.getOriginalFilename();
        
        try {
            File targetFile=new File(filePath);
            logger.info("将图片写入文件:"+ filePath);
            FileUtils.writeByteArrayToFile(targetFile, file.getBytes());
        } catch (IOException e) {
            logger.info("图片写入失败");
            e.printStackTrace();
        }
        return uploadPath + "/" + file.getOriginalFilename();
    }
}

3-5 缩略图生成服务类开发

代码演示:

package com.myimooc.thumbnail.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import net.coobird.thumbnailator.Thumbnails;

/**
 * 缩略图服务类
 * @author ZhangCheng on 2017-07-19
 *
 */
@Service
public class ThumbnailService {
    
    public static final int WIDTH = 100;
    public static final int HEIGHT = 100;
    
    public String thumbnail(MultipartFile file,String uploadPath,String realUploadPath){
        try{
            String des = realUploadPath + "/thum_" + file.getOriginalFilename();
            Thumbnails.of(file.getInputStream()).size(WIDTH, HEIGHT).toFile(des);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return uploadPath + "/thum_" + file.getOriginalFilename();
    }
}

3-6 AWT服务类讲解

代码演示:

package com.myimooc.thumbnail.service;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 缩略图服务类
 * 
 * @author ZhangCheng on 2017-07-19
 *
 */
@Service
public class ThumbnailAWTService {

    public static final int WIDTH = 100;
    public static final int HEIGHT = 100;

    @SuppressWarnings("static-access")
    public String thumbnail(MultipartFile file, String uploadPath, String realUploadPath) {

        OutputStream os = null;

        try {
            String des = realUploadPath + "/thum_" + file.getOriginalFilename();

            os = new FileOutputStream(des);

            Image image = ImageIO.read(file.getInputStream());
            int width = image.getWidth(null);// 原图狂宽度
            int height = image.getHeight(null);// 原图高度

            int rateWidth = width / WIDTH;// 宽度缩略比例
            int rateHeight = height / HEIGHT;// 高度缩略比

            // 宽度缩略比例大于高度缩略比例,使用宽度缩略比例
            int rate = rateWidth > rateHeight ? rateWidth : rateHeight;

            // 计算缩略图最终的宽度和高度
            int newWidth = width / rate;
            int newHeight = height / rate;

            BufferedImage bufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);

            bufferedImage.getGraphics().drawImage(image.getScaledInstance(newWidth, newHeight, image.SCALE_SMOOTH), 0,
                    0, null);

            String imageType = file.getContentType().substring(file.getContentType().indexOf("/") + 1);
            ImageIO.write(bufferedImage, imageType, os);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return uploadPath + "/thum_" + file.getOriginalFilename();
    }
}

3-7 展示页面开发

代码演示:

<html>
<head>
<title>处理结果</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>

    <h2>操作结果</h2>
    
    <table width="100%">
        <tr>
            <td width="50%" aling="center">
                <img src='[@common.ctx /]${imageURL}' width="500" />
            </td>
            <td width="50%" aling="center">
                <img src='[@common.ctx /]${thumImageUrl}' width="100" />
            </td>
        </tr>
    </table>
    <hr />
    <a href='[@common.ctx /]/index'>返回</a>
    
</body>
</html>

效果演示:

启动项目,访问主页

clipboard.png

点击选择图片

clipboard.png

点击上传,结果显示如下

clipboard.png

第四章:课程总结

4-1 课程总结

通过使用开源组件,可以很方便的实现自己需要的功能。可以更加专注于业务逻辑开发,缩短项目开发周期,提高项目开发速度。


妙手空空
1.3k 声望370 粉丝

博观而约取,厚积而薄发