Java 实现图片等比例缩略图 (Thumbnailator + Jsp+SpringMVC)

8 篇文章 0 订阅
7 篇文章 0 订阅

Web应用为上传图片生成缩略图是常见的基本功能,通过缩略图生成提高了信息浏览时的性能,在保证用户使用体验的同时减少了数据传输量。本次以实例的方式,讲解如何使用使用Java实现图片等比例缩略图生成功能。

效果查看

这里写图片描述

这里写图片描述

这里写图片描述

代码编写

Thumbnailator 是一个为Java界面更流畅的缩略图生成库。从API提供现有的图像文件和图像对象的缩略图中简化了缩略过程,两三行代码就能够从现有图片生成缩略图,且允许微调缩略图生成,同时保持了需要写入到最低限度的代码量。

1.导入相关的包

这里写图片描述

2.配置web.xml

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
  <display-name>thumbnail</display-name>
  <!-- 配置 SpringMVC 的 DispatcherServlet -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

3.配置 springmvc.xml

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"    
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>    
    <!-- 配置自定扫描的包 -->
    <context:component-scan base-package="com.wenteryan"></context:component-scan>

    <!-- 配置视图解析器: 如何把 handler 方法返回值解析为实际的物理视图 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
    </bean>

    <bean id="multipartResolver" 
            class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="maxUploadSize" value="10485760000"></property>
        <property name="maxInMemorySize" value="40960"></property>
    </bean>

</beans>

4.编写Action

ThumbnailAction.java

@Controller
public class ThumbnailAction {

    public UploadService uploadService ;
    public ThumbnailService thumbnailService ;

    @RequestMapping(value="/thumbnail", method=RequestMethod.POST)
    public ModelAndView thumbnail(@RequestParam("image")CommonsMultipartFile file, HttpSession session) throws Exception {
        String uploadPath = "/images" ;
        String realUploadPath = session.getServletContext().getRealPath(uploadPath) ;
        String imageUrl = uploadService.uploadImage(file, uploadPath, realUploadPath) ;
        String thumbImageUrl = thumbnailService.thumbnail(file, uploadPath, realUploadPath) ;
        ModelAndView ret = new ModelAndView() ;
        ret.addObject("imagesUrl", imageUrl) ;
        ret.addObject("thumbnailUrl", thumbImageUrl) ;
        ret.setViewName("thumbnail");   
        return ret ;
    }

    @Autowired
    public void setUploadService(UploadService uploadService) {
        this.uploadService = uploadService;
    }
    @Autowired
    public void setThumbnailService(ThumbnailService thumbnailService) {
        this.thumbnailService = thumbnailService;
    }
}

5.编写service

ThumbnailService .java

@Service
public class ThumbnailService {

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

    public String thumbnail(CommonsMultipartFile 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() ;
    }
}

UploadService .java

@Service
public class UploadService {

    public String uploadImage(CommonsMultipartFile file, String uploadPath, String realUploadPath) {
        InputStream is = null ;
        OutputStream os = null ;

        try {
            is = file.getInputStream() ;
            String des = realUploadPath + "\\" + file.getOriginalFilename() ;
            os = new FileOutputStream(des) ;
            byte[] buffer = new byte[1024] ;
            int len = 0 ;
            while((len=is.read(buffer))>0) {
                os.write(buffer);
            }
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            if(is!=null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            if(os!=null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return uploadPath + "/" + file.getOriginalFilename() ;
    }
}

6.编写 jsp 文件

index.jsp

<div class="panel panel-warning">
    <div class="panel-heading"><h2>Java 实现图片等比例缩略图</h2></div>
    <div class="panel-body">
    <form action="thumbnail" method="post" enctype="multipart/form-data">
        <h2>请选择上传的图片</h2>
        <div class="form-group">
        <input type="file" name="image" id="image" />
        </div>
        <div class="form-group">
        <button class="btn btn-success" type="submit">开始上传</button>
        </div>
    </form>
    </div>
</div>

thumbnail.jsp

<div class="panel panel-warning">
    <div class="panel-heading"><h2>原图片与缩略图</h2></div>
    <div class="panel-body">
        <img alt="" src="${pageContext.request.contextPath }${imagesUrl }"/>
        <img alt="" src="${pageContext.request.contextPath }${thumbnailUrl }"/>
        <br><br>
        <a class="btn btn-warning" href="${pageContext.request.contextPath }">返回</a>
    </div>
</div>
技术总结

实现图片缩略图的好处总结如下:

1、节省存储空间。
2、更加灵活响应运营部的多尺寸图片需求。
3、提高程序性能和效率。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
好的,下面是一个使用SpringMVC和Vue.js实现图片上传的示例代码: 前端页面代码(使用Vue.js): ```html <template> <div> <input type="file" ref="fileInput" @change="handleFileUpload" multiple> <button @click="uploadFiles">上传文件</button> </div> </template> <script> export default { data() { return { files: [] } }, methods: { handleFileUpload() { this.files = this.$refs.fileInput.files; }, uploadFiles() { let formData = new FormData(); for (let i = 0; i < this.files.length; i++) { formData.append("files", this.files[i]); } axios.post("/upload", formData, { headers: { "Content-Type": "multipart/form-data" } }).then(response => { console.log(response.data); }).catch(error => { console.log(error); }); } } } </script> ``` 后端代码(使用SpringMVC): ```java @PostMapping("/upload") @ResponseBody public List<String> upload(@RequestParam("files") MultipartFile[] files) throws IOException { List<String> fileNames = new ArrayList<>(); for (MultipartFile file : files) { if (!file.isEmpty()) { String fileName = file.getOriginalFilename(); String uuid = UUID.randomUUID().toString(); String saveFileName = uuid + "_" + fileName; file.transferTo(new File("/path/to/save/" + saveFileName)); fileNames.add(saveFileName); } } return fileNames; } ``` 这个示例代码使用了Vue.js来实现前端页面的交互,使用了axios库来发送文件上传请求。后端使用了SpringMVC的MultipartFile来处理文件上传请求。在处理每个文件时,可以根据需要对文件进行一些额外的处理,例如:获取文件大小、文件类型等。 希望这个示例代码可以帮助到您!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值