java實(shí)現(xiàn)圖片壓縮的思路與代碼
更新時(shí)間:2016年03月23日 14:59:35 作者:有妳很滿促
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)圖片壓縮的思路與代碼,將較大的圖片按照指定的寬高,以寬為基準(zhǔn),或高為基準(zhǔn)按照等比例壓縮圖片,感興趣的小伙伴們可以參考一下
本文實(shí)例為大家分享了java實(shí)現(xiàn)圖片壓縮的相關(guān)代碼,供大家參考,具體內(nèi)容如下
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
public class ImageProcess {
/**
* 圖片
*/
private Image img;
/**
* 寬度
*/
private int width;
/**
* 高度
*/
private int height;
/**
* 文件格式
*/
private String imageFormat;
/**
* 構(gòu)造函數(shù)
* @throws Exception
*/
public ImageProcess(InputStream in,String fileName) throws Exception{
//構(gòu)造Image對(duì)象
img = ImageIO.read(in);
//得到源圖寬
width = img.getWidth(null);
//得到源圖長(zhǎng)
height = img.getHeight(null);
//文件格式
imageFormat = fileName.substring(fileName.lastIndexOf(".")+1);
}
/**
* 按照寬度還是高度進(jìn)行壓縮
* @param w int 最大寬度
* @param h int 最大高度
*/
public byte[] resizeFix(int w, int h) throws IOException {
if (width / height > w / h) {
return resizeByWidth(w);
} else {
return resizeByHeight(h);
}
}
/**
* 以寬度為基準(zhǔn),等比例放縮圖片
* @param w int 新寬度
*/
public byte[] resizeByWidth(int w) throws IOException {
int h = (int) (height * w / width);
return resize(w, h);
}
/**
* 以高度為基準(zhǔn),等比例縮放圖片
* @param h int 新高度
*/
public byte[] resizeByHeight(int h) throws IOException {
int w = (int) (width * h / height);
return resize(w, h);
}
/**
* 強(qiáng)制壓縮/放大圖片到固定的大小
* @param w int 新寬度
* @param h int 新高度
*/
public byte[] resize(int w, int h) throws IOException {
// SCALE_SMOOTH 的縮略算法 生成縮略圖片的平滑度的 優(yōu)先級(jí)比速度高 生成的圖片質(zhì)量比較好 但速度慢
BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );
image.getGraphics().drawImage(img, 0, 0, w, h, null); // 繪制縮小后的圖
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, imageFormat, baos);
return baos.toByteArray();
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,輕松實(shí)現(xiàn)圖片壓縮操作。
相關(guān)文章
Java使用正則表達(dá)式實(shí)現(xiàn)找出數(shù)字功能示例
這篇文章主要介紹了Java使用正則表達(dá)式實(shí)現(xiàn)找出數(shù)字功能,結(jié)合實(shí)例形式分析了Java針對(duì)數(shù)字的匹配查找及非數(shù)字替換操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-03-03
java servlet結(jié)合Oracle搭建java的web開發(fā)環(huán)境
今天我將與大家分享一下我學(xué)JAVA WEB寫的一些小實(shí)例 ,我個(gè)人是不太喜歡書本上的晦澀的概念的,所以我花了更多的時(shí)間在一些應(yīng)用實(shí)例上,我覺得這樣的學(xué)習(xí)方式很適合我,由簡(jiǎn)到繁,由淺入深2015-12-12
Java項(xiàng)目導(dǎo)入IDEA的流程配置以及常見問(wèn)題解決方法
通常一個(gè)團(tuán)隊(duì)中可能有人用eclipse,有人用intelliJ,那么經(jīng)常會(huì)出現(xiàn)需要導(dǎo)入別人用eclipse建好的web項(xiàng)目,下面這篇文章主要給大家介紹了關(guān)于Java項(xiàng)目導(dǎo)入IDEA的流程配置以及常見問(wèn)題解決方法的相關(guān)資料,需要的朋友可以參考下2023-05-05
使用Java創(chuàng)建數(shù)據(jù)透視表并導(dǎo)出為PDF的方法
數(shù)據(jù)透視分析是一種強(qiáng)大的工具,可以幫助我們從大量數(shù)據(jù)中提取有用信息并進(jìn)行深入分析,本文將介紹如何使用Java來(lái)構(gòu)建PivotTable以及實(shí)現(xiàn)數(shù)據(jù)透視分析,并將其導(dǎo)出為PDF2023-10-10

