放大圖像不會導(dǎo)致失真,而縮小圖像將不可避免的失真。Java中也同樣是這樣。但java提供了4個縮放的微調(diào)選項。image.SCALE_SMOOTH //平滑優(yōu)先image.SCALE_FAST//速度優(yōu)先image.SCALE_AREA_AVERAGING //區(qū)域均值image.SCALE_REPLICATE //像素復(fù)制型縮放image.SCALE_DEFAULT //默認(rèn)縮放模式調(diào)用方法Image new_img=old_img.getScaledInstance(1024, 768, Image.SCALE_SMOOTH);得到一張縮放后的新圖。怎么用java代碼放大或縮小圖片不失真。

成都創(chuàng)新互聯(lián)公司主營溫州網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,成都APP應(yīng)用開發(fā),溫州h5重慶小程序開發(fā)搭建,溫州網(wǎng)站營銷推廣歡迎溫州等地區(qū)企業(yè)咨詢
java要實現(xiàn)把一個大圖片壓縮到指定大小的圖片且長寬比不變可以嘗試以下操作:
建立一個AffineTransform
AffineTransform(double m00, double m10, double m01, double m11, double m02, double m12)
轉(zhuǎn)換矩陣,縮放比較簡單(矩陣可以干很多事情,想做圖像處理軟件可以研究下)
[ x'] [ m00 m01 m02 ] [ x ] [ m00x + m01y + m02 ]
[ y'] = [ m10 m11 m12 ] [ y ] = [ m10x + m11y + m12 ]
[ 1 ] [ 0 0 1 ] [ 1 ] [ 1 ]
10倍比較難算(根號10啊,當(dāng)然你想算也行),9倍好點(9的開方是3),m00為1/3,m01為0,m02為0,m10為0,m11為1/3,m12為0。
再建一個AffineTransformOp,把上面的轉(zhuǎn)換傳進(jìn)去
AffineTransformOp(AffineTransform xform, int interpolationType)
最后調(diào)用AffineTransformOp的BufferedImage filter(BufferedImage src, BufferedImage dst) ,src傳原圖片,返回值就是想要的Image,注意是返回值,不是dst,不明白可以看下Java API
此篇轉(zhuǎn)載。
----------------------------------------------------------------------
下面是一段給圖片加上網(wǎng)站logo的代碼,注意第12,13,14行設(shè)置了圖片的壓縮比。本例為不壓縮原圖片。
java 代碼
BufferedImage image = ImageIO.read(new FileInputStream("c:\\base.jpg"));
//讀取圖標(biāo)
BufferedImage image_biao = ImageIO.read(new FileInputStream(
"c:\\logo.gif"));
Graphics2D g = image.createGraphics();
g.drawImage(image_biao, 10, 10, image_biao.getWidth(null),
image_biao.getHeight(null), null);
g.dispose();
FileOutputStream out = new FileOutputStream("c:\\out.jpg");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
param.setQuality(1f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(image);
out.close();
setQuality
public void setQuality(float quality, boolean forceBaseline)
quality取值在 1.0 到 0.0 之間
Some guidelines: 0.75 high quality 0.5 medium quality 0.25 low quality
另外要得到一張指定高度和寬度的圖片的話可以用以下代碼:(接上面代碼)
java 代碼
BufferedImage tag = new BufferedImage(500, 300,image.getType());
tag.getGraphics().drawImage(image, 0, 0, 500, 300, null); //繪制縮小后的圖
FileOutputStream out2 = new FileOutputStream("c:\\out2.jpg");
JPEGImageEncoder encoder2 = JPEGCodec.createJPEGEncoder(out2);
JPEGEncodeParam param2 = encoder.getDefaultJPEGEncodeParam(tag);
param2.setQuality(1f, false);
encoder2.setJPEGEncodeParam(param2);
encoder2.encode(tag);
out2.close();
注意第一行新建 BufferedImage 的時候要使用原圖片的type,這樣可以保證輸出與原圖片相同質(zhì)量的圖片。
也就是圖片壓縮,可以不修改任何大小的壓縮(速度快),也可等比例修改大小壓縮(較慢)
下面這是一段等比例縮小圖片的方法。
public String compressPic(String inputDir, String outputDir,
String inputFileName, String outputFileName, int width,
int height, boolean gp,String hzm) {
try {
if (!image.exists()) {
return "";
}
Image img = ImageIO.read(image);
// 判斷圖片格式是否正確
if (img.getWidth(null) == -1) {
return "no";
} else {
int newWidth; int newHeight;
// 判斷是否是等比縮放
if (gp == true) {
// 為等比縮放計算輸出的圖片寬度及高度
double rate1 = ((double) img.getWidth(null)) / (double) width ;
double rate2 = ((double) img.getHeight(null)) / (double) height ;
// 根據(jù)縮放比率大的進(jìn)行縮放控制
double rate = rate1 rate2 ? rate1 : rate2;
newWidth = (int) (((double) img.getWidth(null)) / rate);
newHeight = (int) (((double) img.getHeight(null)) / rate);
} else {
newWidth = img.getWidth(null); // 輸出的圖片寬度
newHeight = img.getHeight(null); // 輸出的圖片高度
}
BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);
/*
* Image.SCALE_SMOOTH 的縮略算法 生成縮略圖片的平滑度的
* 優(yōu)先級比速度高 生成的圖片質(zhì)量比較好 但速度慢
*/
Image im = img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
tag.getGraphics().drawImage(im, 0, 0, null);
FileOutputStream out = new FileOutputStream(outputDir + outputFileName);
//JPEGImageEncoder可適用于其他圖片類型的轉(zhuǎn)換
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
return "ok";
}
您轉(zhuǎn)換的是圖片的后綴名吧?您這樣的方式已經(jīng)把圖片的信息刪除了!
您去下載一個java圖片壓縮器吧
或者直接在Java下編輯代碼來實習(xí)轉(zhuǎn)換
package com.sun.util.cyw;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* 圖片工具類
* 壓縮圖片大小
* @author Cyw
* @version 1.0
*/
public class ZIPImage {
private File file = null;
private String outPutFilePath;
private String inPutFilePath;
private String inPutFileName;
private boolean autoBuildFileName;
private String outPutFileName;
private int outPutFileWidth = 100; // 默認(rèn)輸出圖片寬
private int outPutFileHeight = 100; // 默認(rèn)輸出圖片高
private static boolean isScaleZoom = true; // 是否按比例縮放
public ZIPImage() {
outPutFilePath = "";
inPutFilePath = "";
inPutFileName = "";
autoBuildFileName = true;
outPutFileName = "";
}
/**
*
* @param ipfp
* 源文件夾路徑
* @param ipfn
* 源文件名
* @param opfp
* 目標(biāo)文件路徑
* @param opfn
* 目標(biāo)文件名
*/
public ZIPImage(String ipfp, String ipfn, String opfp, String opfn) {
outPutFilePath = opfp;
inPutFilePath = ipfp;
inPutFileName = ipfn;
autoBuildFileName = true;
outPutFileName = opfn;
}
/**
*
* @param ipfp
* 源文件夾路徑
* @param ipfn
* 源文件名
* @param opfp
* 目標(biāo)文件路徑
* @param opfn
* 目標(biāo)文件名
* @param aBFN
* 是否自動生成目標(biāo)文件名
*/
public ZIPImage(String ipfp, String ipfn, String opfp, String opfn,
boolean aBFN) {
outPutFilePath = opfp;
inPutFilePath = ipfp;
inPutFileName = ipfn;
autoBuildFileName = aBFN;
outPutFileName = opfn;
}
public boolean isAutoBuildFileName() {
return autoBuildFileName;
}
public void setAutoBuildFileName(boolean autoBuildFileName) {
this.autoBuildFileName = autoBuildFileName;
}
public String getInPutFilePath() {
return inPutFilePath;
}
public void setInPutFilePath(String inPutFilePath) {
this.inPutFilePath = inPutFilePath;
}
public String getOutPutFileName() {
return outPutFileName;
}
public void setOutPutFileName(String outPutFileName) {
this.outPutFileName = outPutFileName;
}
public String getOutPutFilePath() {
return outPutFilePath;
}
public void setOutPutFilePath(String outPutFilePath) {
this.outPutFilePath = outPutFilePath;
}
public int getOutPutFileHeight() {
return outPutFileHeight;
}
public void setOutPutFileHeight(int outPutFileHeight) {
this.outPutFileHeight = outPutFileHeight;
}
public int getOutPutFileWidth() {
return outPutFileWidth;
}
public void setOutPutFileWidth(int outPutFileWidth) {
this.outPutFileWidth = outPutFileWidth;
}
public boolean isScaleZoom() {
return isScaleZoom;
}
public void setScaleZoom(boolean isScaleZoom) {
this.isScaleZoom = isScaleZoom;
}
public String getInPutFileName() {
return inPutFileName;
}
public void setInPutFileName(String inPutFileName) {
this.inPutFileName = inPutFileName;
}
/**
* 壓縮圖片大小
*
* @return boolean
*/
public boolean compressImage() {
boolean flag = false;
try {
if (inPutFilePath.trim().equals("")) {
throw new NullPointerException("源文件夾路徑不存在。");
}
if (inPutFileName.trim().equals("")) {
throw new NullPointerException("圖片文件路徑不存在。");
}
if (outPutFilePath.trim().equals("")) {
throw new NullPointerException("目標(biāo)文件夾路徑地址為空。");
} else {
if (!ZIPImage.mddir(outPutFilePath)) {
throw new FileNotFoundException(outPutFilePath
+ " 文件夾創(chuàng)建失敗!");
}
}
if (this.autoBuildFileName) { // 自動生成文件名
String tempFile[] = getFileNameAndExtName(inPutFileName);
outPutFileName = tempFile[0] + "_cyw." + tempFile[1];
compressPic();
} else {
if (outPutFileName.trim().equals("")) {
throw new NullPointerException("目標(biāo)文件名為空。");
}
compressPic();
}
} catch (Exception e) {
flag = false;
e.printStackTrace();
return flag;
}
return flag;
}
// 圖片處理
private void compressPic() throws Exception {
try {
// 獲得源文件
file = new File(inPutFilePath + inPutFileName);
if (!file.exists()) {
throw new FileNotFoundException(inPutFilePath + inPutFileName
+ " 文件不存在!");
}
Image img = ImageIO.read(file);
// 判斷圖片格式是否正確
if (img.getWidth(null) == -1) {
throw new Exception("文件不可讀!");
} else {
int newWidth;
int newHeight;
// 判斷是否是等比縮放
if (ZIPImage.isScaleZoom == true) {
// 為等比縮放計算輸出的圖片寬度及高度
double rate1 = ((double) img.getWidth(null))
/ (double) outPutFileWidth + 0.1;
double rate2 = ((double) img.getHeight(null))
/ (double) outPutFileHeight + 0.1;
// 根據(jù)縮放比率大的進(jìn)行縮放控制
double rate = rate1 rate2 ? rate1 : rate2;
newWidth = (int) (((double) img.getWidth(null)) / rate);
newHeight = (int) (((double) img.getHeight(null)) / rate);
} else {
newWidth = outPutFileWidth; // 輸出的圖片寬度
newHeight = outPutFileHeight; // 輸出的圖片高度
}
BufferedImage tag = new BufferedImage((int) newWidth,
(int) newHeight, BufferedImage.TYPE_INT_RGB);
/*
* Image.SCALE_SMOOTH 的縮略算法 生成縮略圖片的平滑度的 優(yōu)先級比速度高 生成的圖片質(zhì)量比較好 但速度慢
*/
tag.getGraphics().drawImage(
img.getScaledInstance(newWidth, newHeight,
Image.SCALE_SMOOTH), 0, 0, null);
FileOutputStream out = new FileOutputStream(outPutFilePath
+ outPutFileName);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* 創(chuàng)建文件夾目錄
*
* @param filePath
* @return
* @throws Exception
*/
@SuppressWarnings("unused")
private static boolean mddir(String filePath) throws Exception {
boolean flag = false;
File f = new File(filePath);
if (!f.exists()) {
flag = f.mkdirs();
} else {
flag = true;
}
return flag;
}
/**
* 獲得文件名和擴展名
*
* @param fullFileName
* @return
* @throws Exception
*/
private String[] getFileNameAndExtName(String fullFileName)
throws Exception {
String[] fileNames = new String[2];
if (fullFileName.indexOf(".") == -1) {
throw new Exception("源文件名不正確!");
} else {
fileNames[0] = fullFileName.substring(0, fullFileName
.lastIndexOf("."));
fileNames[1] = fullFileName
.substring(fullFileName.lastIndexOf(".") + 1);
}
return fileNames;
}
public Image getSourceImage() throws IOException{
//獲得源文件
file = new File(inPutFilePath + inPutFileName);
if (!file.exists()) {
throw new FileNotFoundException(inPutFilePath + inPutFileName
+ " 文件不存在!");
}
Image img = ImageIO.read(file);
return img;
}
/*
* 獲得圖片大小
* @path :圖片路徑
*/
public long getPicSize(String path) {
File file = new File(path);
return file.length();
}
}
//下面是測試程序
package com.sun.util.cyw;
import java.awt.Image;
import java.io.IOException;
public class ImageTest {
public static void main(String[] args) throws IOException {
ZIPImage zip=new ZIPImage("d:\\","1.jpg","d:\\test\\","處理后的圖片.jpg",false);
zip.setOutPutFileWidth(1000);
zip.setOutPutFileHeight(1000);
Image image=zip.getSourceImage();
long size=zip.getPicSize("d:\\1.jpg");
System.out.println("處理前的圖片大小 width:"+image.getWidth(null));
System.out.println("處理前的圖片大小 height:"+image.getHeight(null));
System.out.println("處理前的圖片容量:"+ size +" bit");
zip.compressImage();
}
}
可以使用Draw這個類,通過改變像素來改變存儲大小,實例如下:
public?static?boolean?compressPic(String?srcFilePath,?String?descFilePath)?throws?IOException?{
File?file?=?null;
BufferedImage?src?=?null;
FileOutputStream?out?=?null;
ImageWriter?imgWrier;
ImageWriteParam?imgWriteParams;
//?指定寫圖片的方式為?jpg
imgWrier?=?ImageIO.getImageWritersByFormatName("jpg").next();
imgWriteParams?=?new?javax.imageio.plugins.jpeg.JPEGImageWriteParam(
null);
//?要使用壓縮,必須指定壓縮方式為MODE_EXPLICIT
imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
//?這里指定壓縮的程度,參數(shù)qality是取值0~1范圍內(nèi),
imgWriteParams.setCompressionQuality((float)?1);
imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
ColorModel?colorModel?=ImageIO.read(new?File(srcFilePath)).getColorModel();//?ColorModel.getRGBdefault();
//?指定壓縮時使用的色彩模式
//????????imgWriteParams.setDestinationType(new?javax.imageio.ImageTypeSpecifier(
//????????????????colorModel,?colorModel.createCompatibleSampleModel(16,?16)));
imgWriteParams.setDestinationType(new?javax.imageio.ImageTypeSpecifier(
colorModel,?colorModel.createCompatibleSampleModel(16,?16)));
try?{
if?(isBlank(srcFilePath))?{
return?false;
}?else?{
file?=?new?File(srcFilePath);System.out.println(file.length());
src?=?ImageIO.read(file);
out?=?new?FileOutputStream(descFilePath);
imgWrier.reset();
//?必須先指定?out值,才能調(diào)用write方法,?ImageOutputStream可以通過任何
//?OutputStream構(gòu)造
imgWrier.setOutput(ImageIO.createImageOutputStream(out));
//?調(diào)用write方法,就可以向輸入流寫圖片
imgWrier.write(null,?new?IIOImage(src,?null,?null),
imgWriteParams);
out.flush();
out.close();
}
}?catch?(Exception?e)?{
e.printStackTrace();
return?false;
}
return?true;
}
public?static?boolean?isBlank(String?string)?{
if?(string?==?null?||?string.length()?==?0?||?string.trim().equals(""))?{
return?true;
}
return?false;
}
分享文章:java代碼壓縮圖片代碼,java對圖片進(jìn)行壓縮
鏈接分享:http://chinadenli.net/article31/dsihhpd.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供響應(yīng)式網(wǎng)站、網(wǎng)站營銷、網(wǎng)站收錄、網(wǎng)站導(dǎo)航、網(wǎng)站內(nèi)鏈、全網(wǎng)營銷推廣
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)