java完成圖片緊縮的思緒與代碼。本站提示廣大學習愛好者:(java完成圖片緊縮的思緒與代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是java完成圖片緊縮的思緒與代碼正文
本文實例為年夜家分享了java完成圖片緊縮的相干代碼,供年夜家參考,詳細內容以下
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;
/**
* 結構函數
* @throws Exception
*/
public ImageProcess(InputStream in,String fileName) throws Exception{
//結構Image對象
img = ImageIO.read(in);
//獲得源圖寬
width = img.getWidth(null);
//獲得源圖長
height = img.getHeight(null);
//文件格局
imageFormat = fileName.substring(fileName.lastIndexOf(".")+1);
}
/**
* 依照寬度照樣高度停止緊縮
* @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);
}
}
/**
* 以寬度為基准,等比例放縮圖片
* @param w int 新寬度
*/
public byte[] resizeByWidth(int w) throws IOException {
int h = (int) (height * w / width);
return resize(w, h);
}
/**
* 以高度為基准,等比例縮放圖片
* @param h int 新高度
*/
public byte[] resizeByHeight(int h) throws IOException {
int w = (int) (width * h / height);
return resize(w, h);
}
/**
* 強迫緊縮/縮小圖片到固定的年夜小
* @param w int 新寬度
* @param h int 新高度
*/
public byte[] resize(int w, int h) throws IOException {
// SCALE_SMOOTH 的縮略算法 生成縮略圖片的膩滑度的 優先級比速度高 生成的圖片質量比擬好 但速度慢
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();
}
}
以上就是本文的全體內容,願望對年夜家的進修有所贊助,輕松完成圖片緊縮操作。