使用Thumbnailator压缩照片
生活随笔
收集整理的這篇文章主要介紹了
使用Thumbnailator压缩照片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
導入依賴
<dependency><groupId>net.coobird</groupId><artifactId>thumbnailator</artifactId><version>0.4.8</version></dependency>代碼
package com.asx.hyd.non.trs;import net.coobird.thumbnailator.Thumbnails;import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import java.util.Random;public class Test {public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {File file = new File("/Users/4paradigm/Desktop/11112.jpeg");compressImage(file);}public static InputStream compressImage(File file) {InputStream inputStream = null;try {FileInputStream fileInputStream = new FileInputStream(file);inputStream = fileInputStream;BufferedImage image = ImageIO.read(file);int width = image.getWidth();int height = image.getHeight();int newHeight = 0;int newWidth = 0;if (width > 900) {newWidth = 1360;newHeight = height * 1360 / width;//按指定大小把圖片進行縮和放(會遵循原圖高寬比例)ByteArrayOutputStream outputStream = new ByteArrayOutputStream();ImageIO.write(image, "jpg", outputStream);byte[] bytes = outputStream.toByteArray();ByteArrayOutputStream out = new ByteArrayOutputStream(bytes.length);Thumbnails.of(inputStream).size(newWidth, newHeight).toOutputStream(out);//變?yōu)?360 * 對應比例,遵循原圖比例縮放byte[] b = out.toByteArray();//將圖片寫到本地BufferedOutputStream stream=null;Random random = new Random(25);int i = random.nextInt(1000);String randomNum= String.valueOf(i);String tagFileName="/Users/4paradigm/Desktop/"+File.separator+"壓縮后的照片"+randomNum+"22.jpeg";File fileout = new File(tagFileName);FileOutputStream fileOutputStream = new FileOutputStream(fileout);stream = new BufferedOutputStream(fileOutputStream);stream.write(b);stream.close();System.out.println("----------------壓縮圖片尺寸后大小-------------: " + b.length/1024+"K");inputStream = new ByteArrayInputStream(out.toByteArray());}} catch (IOException e) {e.printStackTrace();}return inputStream;} }Thumbnailator的簡介和使用范例
https://www.jianshu.com/p/ad8af8214e60
https://blog.csdn.net/qq_34839150/article/details/109903432
總結
以上是生活随笔為你收集整理的使用Thumbnailator压缩照片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微信小程序怎么看使用时间如何查询电脑使用
- 下一篇: 关闭zookeeper进程