java
package com.app.image;import java.io.*;import java.util.Date;import java.awt.*;import java.awt.image.*;import javax.imageio.ImageIO;import com.sun.image.codec.jpeg.*;/** * 圖片壓縮處理 * @author 崔素強 */public class ImageThumbOrCompress {private Image img;private int width;private int height;public static void main(String[] args) throws Exception {System.out.println("開始:" + new Date().toLocaleString());ImageThumbOrCompress imgCom = new ImageThumbOrCompress("D:/Droid4x/test.jpg");imgCom.resizeFix(400, 400);System.out.println("結束:" + new Date().toLocaleString());}/** * 建構函式 */public ImageThumbOrCompress(String fileName) throws IOException {File file = new File(fileName);// 讀入檔案img = ImageIO.read(file); // 構造Image對象width = img.getWidth(null); // 得到源圖寬height = img.getHeight(null); // 得到源圖長}/** * 按照寬度還是高度進行壓縮 * @param w int 最大寬度 * @param h int 最大高度 */public void resizeFix(int w, int h) throws IOException {if (width / height > w / h) {resizeByWidth(w);} else {resizeByHeight(h);}}/** * 以寬度為基準,等比例放縮圖片 * @param w int 新寬度 */public void resizeByWidth(int w) throws IOException {int h = (int) (height * w / width);resize(w, h);}/** * 以高度為基準,等比例縮放圖片 * @param h int 新高度 */public void resizeByHeight(int h) throws IOException {int w = (int) (width * h / height);resize(w, h);}/** * 強制壓縮/放大圖片到固定的大小 * @param w int 新寬度 * @param h int 新高度 */public void resize(int w, int h) throws IOException {// SCALE_SMOOTH 的縮減演算法 產生縮圖片的平滑度的 優先順序比速度高 產生的圖片品質比較好 但速度慢BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB ); /*image.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight,Image.SCALE_SMOOTH), 0, 0, null);**/image.getGraphics().drawImage(img, 0, 0, w, h, null); // 繪製縮小後的圖File destFile = new File("D:/Droid4x/test2.jpg");FileOutputStream out = new FileOutputStream(destFile); // 輸出到檔案流// 可以正常實現bmp、png、gif轉jpgJPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);encoder.encode(image); // JPEG編碼out.close();}}
另外,在jdk6以上實現了圖片大小不變,品質改變的壓縮
package com.app.image;import java.awt.image.BufferedImage;import java.awt.image.ColorModel;import java.io.File;import java.io.FileOutputStream;import javax.imageio.IIOImage;import javax.imageio.ImageIO;import javax.imageio.ImageWriteParam;import javax.imageio.ImageWriter;public class ImageQualityCompress {public static void main(String[] args) { if(compressPic("D:/Droid4x/test.jpg", "D:/Droid4x/test3.jpg")) { System.out.println("壓縮成功!"); } else { System.out.println("壓縮失敗!"); } } public static boolean compressPic(String srcFilePath, String descFilePath) { 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); // 這裡指定壓縮的程度,參數qality是取值0~1範圍內, imgWriteParams.setCompressionQuality(0.1f); imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED); ColorModel colorModel = ColorModel.getRGBdefault(); // 指定壓縮時使用的色彩模式 imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel, colorModel .createCompatibleSampleModel(16, 16))); try { if(srcFilePath==null || srcFilePath.length()==0) { return false; } else { file = new File(srcFilePath); src = ImageIO.read(file); out = new FileOutputStream(descFilePath); imgWrier.reset(); // 必須先指定 out值,才能調用write方法, ImageOutputStream可以通過任何 OutputStream構造 imgWrier.setOutput(ImageIO.createImageOutputStream(out)); // 調用write方法,就可以向輸入資料流寫圖片 imgWrier.write(null, new IIOImage(src, null, null), imgWriteParams); out.flush(); out.close(); } } catch(Exception e) { e.printStackTrace(); return false; } return true; }}
php
//by MoreWindows (http://blog.csdn.net/MoreWindows )class CImage{ /** * 產生保持原圖縱橫比的縮圖,支援.png .jpg .gif * 縮圖類型統一為.png格式 * $srcFile 原影像檔名稱 * $toW 縮圖寬 * $toH 縮圖高 * $toFile 縮圖檔案名稱,為空白覆蓋原影像檔 * @return bool */ public static function CreateThumbnail($srcFile, $toW, $toH, $toFile="") { if ($toFile == "") { $toFile = $srcFile; } $info = ""; //返回含有4個單元的數組,0-寬,1-高,2-映像類型,3-寬高的文本描述。 //失敗返回false併產生警告。 $data = getimagesize($srcFile, $info); if (!$data) return false; //將檔案載入到資源變數im中 switch ($data[2]) //1-GIF,2-JPG,3-PNG { case 1: if(!function_exists("imagecreatefromgif")) { echo "the GD can't support .gif, please use .jpeg or .png! back"; exit(); } $im = imagecreatefromgif($srcFile); break; case 2: if(!function_exists("imagecreatefromjpeg")) { echo "the GD can't support .jpeg, please use other picture! back"; exit(); } $im = imagecreatefromjpeg($srcFile); break; case 3: $im = imagecreatefrompng($srcFile); break; } //計算縮圖的寬高 $srcW = imagesx($im); $srcH = imagesy($im); $toWH = $toW / $toH; $srcWH = $srcW / $srcH; if ($toWH <= $srcWH) { $ftoW = $toW; $ftoH = (int)($ftoW * ($srcH / $srcW)); } else { $ftoH = $toH; $ftoW = (int)($ftoH * ($srcW / $srcH)); } if (function_exists("imagecreatetruecolor")) { $ni = imagecreatetruecolor($ftoW, $ftoH); //建立一個真彩色映像 if ($ni) { //重採樣拷貝部分映像並調整大小 可保持較好的清晰度 imagecopyresampled($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH); } else { //拷貝部分映像並調整大小 $ni = imagecreate($ftoW, $ftoH); imagecopyresized($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH); } } else { $ni = imagecreate($ftoW, $ftoH); imagecopyresized($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH); } //儲存到檔案 統一為.png格式 imagepng($ni, $toFile); //以 PNG 格式將映像輸出到瀏覽器或檔案 ImageDestroy($ni); ImageDestroy($im); return true; }}
來自: http://my.oschina.net/ososchina/blog/482951