使用Thumbnails压缩或放大图片大小(java)
生活随笔
收集整理的這篇文章主要介紹了
使用Thumbnails压缩或放大图片大小(java)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
首先看下縮放圖片的核心代碼,其實只有一行而已
//ins表示ByteArrayInputStream形式的圖片 //scale中的數(shù)據(jù)就是縮小或者放大的比例,比如小于1則表示壓縮,大于1表示放大 //out表示ByteArrayOutputStream形式的輸出數(shù)據(jù) 也就是ins縮放后的圖片數(shù)據(jù) Thumbnails.of(ins).scale(0.99f).toOutputStream(out);整體代碼:
為了方便起見,我把整個代碼全拿過來了,防止導(dǎo)錯包,所以使用的話直接復(fù)制即可使用
說明我這里壓縮的圖片是base64格式的圖片,已經(jīng)去掉base64頭部信息,關(guān)于如何去除頭部信息已經(jīng)獲取圖片大小可以參考以下鏈接
獲取base64編碼格式的圖片大小
package com.web.framework.bbpp.module.yituhezisone.util;import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import net.coobird.thumbnailator.Thumbnails; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder;public class CompressImage {public static void main(String[] args) {String str = "base64編碼格式的圖片";CompressImage com = new CompressImage();//因為我使用的是base64編碼格式的圖片數(shù)據(jù),所以需要先將base轉(zhuǎn)為字節(jié)數(shù)組byte[] decode = com.decode(str);//將字節(jié)數(shù)組數(shù)據(jù)傳入壓縮方法中compressByteImagestr = com.compressByteImage(decode);System.out.println("壓縮后的圖片數(shù)據(jù)"+str);}/*** byte數(shù)組 轉(zhuǎn)換為 Base64字符串*/public String encode(byte[] data) {return new BASE64Encoder().encode(data);}/*** Base64字符串 轉(zhuǎn)換為 byte數(shù)組*/public byte[] decode(String base64) {try {return new BASE64Decoder().decodeBuffer(base64);} catch (IOException e) {e.printStackTrace();}return new byte[0];}public String compressByteImage(byte[] bytes) throws IOException {//先將字節(jié)數(shù)組數(shù)據(jù)轉(zhuǎn)為ByteArrayInputStream 形式ByteArrayInputStream ins = new ByteArrayInputStream(bytes);ByteArrayOutputStream out = new ByteArrayOutputStream();//進(jìn)行壓縮 out就是壓縮后的數(shù)據(jù)Thumbnails.of(ins).scale(0.99f).toOutputStream(out);//將ByteArrayOutputStream形式轉(zhuǎn)為字節(jié)數(shù)組byte[] data = out.toByteArray();//將字節(jié)數(shù)組數(shù)據(jù)轉(zhuǎn)為base64的格式String imageStr = encode(data);return imageStr;}總結(jié)
以上是生活随笔為你收集整理的使用Thumbnails压缩或放大图片大小(java)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 将信息写入TXT文本中(java)
- 下一篇: 将时间戳转为年月日时分秒格式