導航:首頁 > 文件處理 > java圖片大小壓縮

java圖片大小壓縮

發布時間:2023-06-07 17:21:32

java壓縮png圖片

您轉換的是圖片的後綴名吧?您這樣的方式已經把圖片的信息刪除了!
http://sjbbs.zol.com.cn/1/313_9068.html您去下載一個java圖片壓縮器吧
或者直接在Java下編輯代碼來實習轉換
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; // 默認輸出圖片寬

private int outPutFileHeight = 100; // 默認輸出圖片高

private static boolean isScaleZoom = true; // 是否按比例縮放

public ZIPImage() {
outPutFilePath = "";
inPutFilePath = "";
inPutFileName = "";
autoBuildFileName = true;
outPutFileName = "";
}

/**
*
* @param ipfp
* 源文件夾路徑
* @param ipfn
* 源文件名
* @param opfp
* 目標文件路徑
* @param opfn
* 目標文件名
*/
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
* 目標文件路徑
* @param opfn
* 目標文件名
* @param aBFN
* 是否自動生成目標文件名
*/
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("目標文件夾路徑地址為空。");
} else {
if (!ZIPImage.mddir(outPutFilePath)) {
throw new FileNotFoundException(outPutFilePath
+ " 文件夾創建失敗!");
}
}

if (this.autoBuildFileName) { // 自動生成文件名
String tempFile[] = getFileNameAndExtName(inPutFileName);
outPutFileName = tempFile[0] + "_cyw." + tempFile[1];
compressPic();
} else {
if (outPutFileName.trim().equals("")) {
throw new NullPointerException("目標文件名為空。");
}
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;

// 根據縮放比率大的進行縮放控制
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 的縮略演算法 生成縮略圖片的平滑度的 優先順序比速度高 生成的圖片質量比較好 但速度慢
*/
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();
}
}

/**
* 創建文件夾目錄
*
* @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();
}
}

⑵ java如何實現壓縮圖片且保留圖片原文件屬性,比如拍攝日期

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;public class Zip {
// 壓縮
public static void zip(String zipFileName, String inputFile)
throws Exception {
File f = new File(inputFile);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
zipFileName));
zip(out, f, null);
System.out.println("zip done");
out.close();
} private static void zip(ZipOutputStream out, File f, String base)
throws Exception {
System.out.println("zipping " + f.getAbsolutePath());
if (f != null && f.isDirectory()) {
File[] fc = f.listFiles();
if (base != null)
out.putNextEntry(new ZipEntry(base + "/"));
base = base == null ? "" : base + "/";
for (int i = 0; i < fc.length; i++) {
zip(out, fc[i], base + fc[i].getName());
}
} else {
out.putNextEntry(new ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
while ((b = in.read()) != -1)
out.write(b);
in.close();
}
} // 解壓
public static void unzip(String zipFileName, String outputDirectory)
throws Exception {
ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName));
ZipEntry z;
while ((z = in.getNextEntry()) != null) {
String name = z.getName();
if (z.isDirectory()) {
name = name.substring(0, name.length() - 1);
File f = new File(outputDirectory + File.separator + name);
f.mkdir();
System.out.println("MD " + outputDirectory + File.separator
+ name);
} else {
System.out.println("unziping " + z.getName());
File f = new File(outputDirectory + File.separator + name);
f.createNewFile();
FileOutputStream out = new FileOutputStream(f);
int b;
while ((b = in.read()) != -1)
out.write(b);
out.close();
}
}
in.close();
} public void deleteFolder(File dir) {
File filelist[] = dir.listFiles();
int listlen = filelist.length;
for (int i = 0; i < listlen; i++) {
if (filelist[i].isDirectory()) {
deleteFolder(filelist[i]);
} else {
filelist[i].delete();
}
}
dir.delete();// 刪除當前目錄
} public static void main(String[] args) {
try {
// TestZip t = new TestZip();
// t.zip("c:\\test.zip","c:\\test");
// t.unzip("c:\\test.zip","c:\\test2");
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}

⑶ java thumbnails壓縮圖片佔用內存過大

縮小即可。javathumbnails壓縮圖片佔用內存過大的解決辦法:
1、打開壓縮圖網站,點擊選擇圖片壓縮按鈕。
2、圖片上傳前網站默認的壓縮等級是70,圖片上傳後會自動按照當前設置的壓縮等級進行壓縮,如果壓縮後的大小不合要求,可再次設置圖片的寬高尺寸、壓縮等級等參數,寬高留空時默認按照原圖尺寸進行壓縮,壓縮等級越小則壓縮後的圖片體積越小,最後點擊開始壓縮按鈕重新壓縮。
3、圖片壓縮後,我們就能明顯的看到圖片壓縮後的體積縮小了很多,點擊「保存圖片」即可。

⑷ Java上傳pdf文件,只壓縮大小,不改變成.zip/.rar文件

Java上傳pdf文件,只壓縮大小,不改變成.zip/.rar文件
可以,壓縮只是一種演算法,什麼語言都可以,比如某種格式的文件中1001010(二進制)代表漢子的"中"字,那麼壓縮演算法就是在編碼不沖突的情況下可以改變編碼長度,比如壓縮之後中字變成1010,這樣就節省空間了,這是我隨便舉的例子,具體的對應演算法可以網上查

⑸ java如何實現把一個大圖片壓縮到指定大小的圖片且長寬比不變

java要實現把一個大圖片壓縮到指定大小的圖片且長寬比不變可以嘗試以下操作:

⑹ 求助java壓縮圖片存儲大小的方法

可以使用Draw這個類,通過改變像素來改變存儲大小,實例如下:

(StringsrcFilePath,StringdescFilePath)throwsIOException{
Filefile=null;
BufferedImagesrc=null;
FileOutputStreamout=null;
ImageWriterimgWrier;
ImageWriteParamimgWriteParams;

//指定寫圖片的方式為jpg
imgWrier=ImageIO.getImageWritersByFormatName("jpg").next();
imgWriteParams=newjavax.imageio.plugins.jpeg.JPEGImageWriteParam(
null);
//要使用壓縮,必須指定壓縮方式為MODE_EXPLICIT
imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
//這里指定壓縮的程度,參數qality是取值0~1范圍內,
imgWriteParams.setCompressionQuality((float)1);
imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
ColorModelcolorModel=ImageIO.read(newFile(srcFilePath)).getColorModel();//ColorModel.getRGBdefault();
//指定壓縮時使用的色彩模式
//imgWriteParams.setDestinationType(newjavax.imageio.ImageTypeSpecifier(
//colorModel,colorModel.createCompatibleSampleModel(16,16)));
imgWriteParams.setDestinationType(newjavax.imageio.ImageTypeSpecifier(
colorModel,colorModel.createCompatibleSampleModel(16,16)));

try{
if(isBlank(srcFilePath)){
returnfalse;
}else{
file=newFile(srcFilePath);System.out.println(file.length());
src=ImageIO.read(file);
out=newFileOutputStream(descFilePath);

imgWrier.reset();
//必須先指定out值,才能調用write方法,ImageOutputStream可以通過任何
//OutputStream構造
imgWrier.setOutput(ImageIO.createImageOutputStream(out));
//調用write方法,就可以向輸入流寫圖片
imgWrier.write(null,newIIOImage(src,null,null),
imgWriteParams);
out.flush();
out.close();
}
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
returntrue;
}
publicstaticbooleanisBlank(Stringstring){
if(string==null||string.length()==0||string.trim().equals("")){
returntrue;
}
returnfalse;
}

⑺ java 實現圖片zip壓縮後,圖片容量越來越大

這個跟壓縮演算法有關系,其中有一些小體積文件確實會產生壓縮後體積增大的現象。

⑻ 如何用java 調整jepg圖片壓縮

ImageWriter writer; // 自己獲取 ImageWriter 對象
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
// 參數為0和1
// 1表示設置最小的壓縮以保持最大的圖片質量
iwp.setCompressionQuality(1);
File file = new File(OUTPUTFILE);
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(BUFFEREDIMAGE, null, null);
// 寫入圖片
writer.write(null, image, iwp);
writer.dispose()
問了一下我遠標教育的哥們,希望對你有用!

⑼ java如何實現把一個大圖片壓縮到指定大小的圖片且長寬比不變

java要實現把一個大圖片壓縮到指定大小的圖片且長寬比不變可以嘗試以下操作:

  1. 建立一個AffineTransform

  2. AffineTransform(double m00, double m10, double m01, double m11, double m02, double m12)

  3. 轉換矩陣,縮放比較簡單(矩陣可以干很多事情,想做圖像處理軟體可以研究下)
    [ x'] [ m00 m01 m02 ] [ x ] [ m00x + m01y + m02 ]
    [ y'] = [ m10 m11 m12 ] [ y ] = [ m10x + m11y + m12 ]
    [ 1 ] [ 0 0 1 ] [ 1 ] [ 1 ]

  4. 10倍比較難算(根號10啊,當然你想算也行),9倍好點(9的開方是3),m00為1/3,m01為0,m02為0,m10為0,m11為1/3,m12為0。

  5. 再建一個AffineTransformOp,把上面的轉換傳進去
    AffineTransformOp(AffineTransform xform, int interpolationType)

  6. 最後調用AffineTransformOp的BufferedImage filter(BufferedImage src, BufferedImage dst) ,src傳原圖片,返回值就是想要的Image,注意是返回值,不是dst,不明白可以看下Java API

閱讀全文

與java圖片大小壓縮相關的資料

熱點內容
示波器app怎麼看 瀏覽:612
米家app英文怎麼改 瀏覽:605
學習編程你有什麼夢想 瀏覽:886
農行信用報告解壓密碼 瀏覽:217
小程序員調試信息 瀏覽:183
電腦打代碼自帶編譯嗎 瀏覽:273
和平怎麼在和平營地轉安卓 瀏覽:463
我的世界中如何查看伺服器的人數 瀏覽:618
台式機改為網路伺服器有什麼好處 瀏覽:960
騰訊雲輕量應用伺服器如何登陸 瀏覽:620
考研復試c語言編譯器 瀏覽:150
安卓的字體怎麼變粗 瀏覽:253
java錯誤無法載入主類 瀏覽:348
程序員考試考什麼文憑 瀏覽:883
pdf版破解 瀏覽:522
安卓系統如何重啟 瀏覽:174
小天才app鬧鍾怎麼改 瀏覽:962
司馬彥PDF 瀏覽:885
動力轉向編程 瀏覽:831
史瓦格期貨基本分析pdf 瀏覽:811