當前位置:首頁 » 文件管理 » java上傳圖片壓縮

java上傳圖片壓縮

發布時間: 2022-11-22 08:15:38

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實現壓縮視頻文件,但是壓縮後並解壓,提示文件損壞,我該怎麼修改代碼

(1)網路傳輸狀況不好(如斷線過多,開的線程過多,伺服器人太多導致不能連接太多等)導致下載下來的文件損壞!
(2)站點提供的的RAR壓縮包本來就是損壞的(這個本站可以保證,所上傳的視頻及軟體等都經過好幾遍測試,絕對沒問題)。
(3)所使用的下載工具不夠完善,比如有的下載工具多開了幾個線程後,下載的收尾工作很慢,有些時候下載到99%時數據就不再傳輸了,一定要人工操作才能結束(先停止下載接著再開始)。筆者就碰到過好幾次這樣的情況。結果是文件下載下來以後解壓縮到快結束時CRC出錯。
解決方法:本站為防止這樣的事情發生,在每個壓縮包里又加了一個備份,防止因以上原因導致的下載後不能用,還得重新下載的問題,只要你下載下來的那個壓縮包里的備份是好的那就能把壓縮包里的文件恢復能用。
步驟一:雙擊打開需要解壓修復的壓縮包,選擇:工具——修復壓縮文件。
步驟二:出現下邊圖片的修復框,等待修復完成,關閉窗口及解壓縮窗口就可以了。
步驟三:這時你會發現你需要解壓的壓縮包旁邊多了一個壓縮包,名稱為:fixed.***(你下載的視頻名稱).rar ,這個壓縮包就是修復後的解壓縮包,如果修復成功,解壓這個名稱為:fixed.***(你下載的視頻名稱).rar 的壓縮包就可以了。
如果修復不成功,你再修復幾次看看,如果不行,只有再重新下載了

③ java壓縮圖片速度慢 怎麼優化

緩存什麼的沒關系。
跟圖片大小,網速、帶寬 有關

圖片不能太大,一般網站都會對上傳的 圖片進行縮略,壓縮處理

一般都會把圖片處理成三或四 種規格:縮略圖,中圖,大圖,原圖
不要把原圖直接放在頁面上,根據需求盡量用最小的圖。 這樣頁面載入就會很快。

不要用TOMCAT壓縮圖片,會很占伺服器資源的。而且大部分圖片都是已經壓縮過的只是像素太高,實際頁面顯示的時候根本不需要太高的像素,主要是要對圖片像素大小進行處理。
怎麼實現你可以搜一下java 圖片處理 圖片縮略
http://www..com/s?wd=52017731337

④ 求助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 如何壓縮文件

樓主是說解壓了的文件大小隻有33.1MB,但是卻佔了51.2MB的空間嗎?
如果是這個意思的話,那我要告訴樓主,首先這個問題和JAVA沒有關系,根據你的截圖,可以斷定你用的是FAT32文件系統。這只是文件存儲的形式,很正常。
簡單的說,磁碟存儲數據的最小單位是簇,比方說你的簇大小為128K,一個簇只能存放一個文件,然後你的一個文件只有16K,它佔了這個簇,然後還有112K沒有用,是吧。但是那112K就不能再存放其它文件了。如果要存放其它文件,就要佔另一個簇。
樓主,懂了吧,這跟簇的大小有關,但是也不是簇越小越好,簇越小,讀寫性能都有所下降。這是正常現象。如果你非覺得不舒服,那就用NTFS文件系統吧,把壓縮打開,就不會有這種情況了,希望對你有幫助

⑥ java上傳圖片 生成縮略圖,如果上傳的圖片尺寸比較小就壓縮處理

//將圖按比例縮小。
public static BufferedImage resize(BufferedImage source, int targetW, int targetH) {
// targetW,targetH分別表示目標長和寬
int type = source.getType();
BufferedImage target = null;
double sx = (double) targetW / source.getWidth();
double sy = (double) targetH / source.getHeight();
//這里想實現在targetW,targetH范圍內實現等比縮放。如果不需要等比縮放
//則將下面的if else語句注釋即可
if(sx>sy)
{
sx = sy;
targetW = (int)(sx * source.getWidth());
}else{
sy = sx;
targetH = (int)(sy * source.getHeight());
}
if (type == BufferedImage.TYPE_CUSTOM) { //handmade
ColorModel cm = source.getColorModel();
WritableRaster raster = cm.(targetW, targetH);
boolean alphaPremultiplied = cm.isAlphaPremultiplied();
target = new BufferedImage(cm, raster, alphaPremultiplied, null);
} else
target = new BufferedImage(targetW, targetH, type);
Graphics2D g = target.createGraphics();
//smoother than exlax:
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY );
g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
g.dispose();
return target;
}

public static void saveImageAsJpg (String fromFileStr,String saveToFileStr,int width,int hight)
throws Exception {
BufferedImage srcImage;
// String ex = fromFileStr.substring(fromFileStr.indexOf("."),fromFileStr.length());
String imgType = "JPEG";
if (fromFileStr.toLowerCase().endsWith(".png")) {
imgType = "PNG";
}
// System.out.println(ex);
File saveFile=new File(saveToFileStr);
File fromFile=new File(fromFileStr);
srcImage = ImageIO.read(fromFile);
if(width > 0 || hight > 0)
{
srcImage = resize(srcImage, width, hight);
}
ImageIO.write(srcImage, imgType, saveFile);

}

public static void main (String argv[]) {
try{
//參數1(from),參數2(to),參數3(寬),參數4(高)
saveImageAsJpg("C:\\Documents and Settings\\xugang\\桌面\\tmr-06.jpg",
"C:\\Documents and Settings\\xugang\\桌面\\2.jpg",
120,120);
} catch(Exception e){
e.printStackTrace();
}

}

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

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

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

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

⑨ java ssh實現微信端操作 有圖片上傳的地方 怎麼能在上傳到伺服器之前進行等比例壓縮

public class struts2UploadAction extends ActionSupport {

private File uploadFile;// 得到上傳的文件

private String uploadFileContentType;// 得到文件的類型

private String uploadFileFileName;// 得到文件的名稱

public String load() throws IOException {

String RealPath = ServletActionContext.getServletContext().getRealPath("/piction");
File file = new File(RealPath);
if(!file.exists()){
file.mkdirs();
}
FileUtils.File(uploadFile, new File(file,uploadFileFileName));
String path=RealPath+"/"+uploadFileFileName;
ServletActionContext.getRequest().setAttribute("realpath",path);
return "success";
}

public File getUploadFile() {
return uploadFile;
}

public void setUploadFile(File uploadFile) {
this.uploadFile = uploadFile;
}

public String getUploadFileContentType() {
return uploadFileContentType;
}

public void setUploadFileContentType(String uploadFileContentType) {
this.uploadFileContentType = uploadFileContentType;
}

public String getUploadFileFileName() {
return uploadFileFileName;
}

public void setUploadFileFileName(String uploadFileFileName) {
this.uploadFileFileName = uploadFileFileName;
}
}

熱點內容
微指令的編譯方法有哪一些 發布:2024-10-05 19:02:10 瀏覽:884
android離線定位 發布:2024-10-05 18:36:40 瀏覽:858
ipad4密碼忘記怎麼辦 發布:2024-10-05 18:36:07 瀏覽:237
黑莓加密天線 發布:2024-10-05 18:30:07 瀏覽:849
編程入行年齡 發布:2024-10-05 18:29:24 瀏覽:538
伺服器地址訪問不到 發布:2024-10-05 18:20:55 瀏覽:689
手機解鎖忘記密碼多少錢 發布:2024-10-05 18:14:25 瀏覽:785
linux亂碼問題 發布:2024-10-05 18:00:25 瀏覽:543
訪客儀需要電腦做伺服器嗎 發布:2024-10-05 17:57:57 瀏覽:10
怎麼在u盤設置密碼 發布:2024-10-05 17:55:23 瀏覽:580