慕課網_《Java實現圖片等比例縮略圖》學習總結

時間:2017年07月15日星期六
說明:本文部份內容均來自慕課網。@慕課網:http://www.imooc.com
教學源碼:無
學習源碼:https://github.com/zccodere/s...html

第一章:課程介紹

1-1 課程介紹

在用戶進行信息概略瀏覽的時候,提供縮略圖java

提高程序性能
提高程序效率

課程內容git

Java圖片等比縮略圖實現方式介紹
課程項目案例介紹
實現圖片等比縮略圖的生成

1-2 實現方式

實現方式github

Thumbnailator類庫:
    推薦使用
    size()API方法
Java AWT類庫:
    根據縮略比例計算縮略圖高度和寬度
    使用Image類得到原圖的縮放版本
    使用ImageIO類保存縮略圖
    BufferedImage類
    ImageIO類
    Graphics類

第二章:案例介紹

2-1 案例介紹

案例介紹web

基於springmvc框架的Java Web應用程序,容許上傳圖片,並生成圖片的縮略圖

效果示意圖spring

clipboard.png

clipboard.png

第三章:案例實現

3-1 框架搭建

我的學習時,使用springboot+freemaker+mavem搭建,POM文件以下apache

<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>

項目層級結構以下springboot

clipboard.png

3-2 上傳頁面開發

代碼演示:mvc

<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 控制器開發

代碼演示:app

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 課程總結

經過使用開源組件,能夠很方便的實現本身須要的功能。能夠更加專一於業務邏輯開發,縮短項目開發週期,提升項目開發速度。

相關文章
相關標籤/搜索