Java 後端壓縮圖片

來源:互聯網
上載者:User

標籤:png   class   encode   getwidth   url   util   size   結束   create   

import java.io.*;
import java.util.Date;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.ImageIO;
//import com.sun.image.codec.jpeg.*;

public class ImgCompress {
private Image img;
private int width;
private int height;

@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
System.out.println("開始:" + new Date().toLocaleString());
ImgCompress imgCom = new ImgCompress("C:\\Users\\fh123\\Desktop\\TIM圖片20180511172046.jpg");
imgCom.resizeFix(600, 600,"C:\\Users\\fh123\\Desktop\\TIM圖片20180511172046.jpg");
System.out.println("結束:" + new Date().toLocaleString());
}

public ImgCompress(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,String urlPath) throws IOException {
if (width / height > w / h) {
resizeByWidth(w,urlPath);
} else {
resizeByHeight(h,urlPath);
}
}

/**
* 以寬度為基準,等比例放縮圖片
*
* @param w
* int 新寬度
*/
public void resizeByWidth(int w,String urlPath) throws IOException {
int h = (int) (height * w / width);
resize(w, h,urlPath);
}

/**
* 以高度為基準,等比例縮放圖片
*
* @param h
* int 新高度
*/
public void resizeByHeight(int h,String urlPath) throws IOException {
int w = (int) (width * h / height);
resize(w, h,urlPath);
}

/**
* 強制壓縮/放大圖片到固定的大小
*
* @param w
* int 新寬度
* @param h
* int 新高度
*/
public void resize(int w, int h,String urlPath) throws IOException {
// SCALE_SMOOTH 的縮減演算法 產生縮圖片的平滑度的 優先順序比速度高 產生的圖片品質比較好 但速度慢
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
image.getGraphics().drawImage(img, 0, 0, w, h, null); // 繪製縮小後的圖
File destFile = new File(urlPath);
FileOutputStream out = new FileOutputStream(destFile); // 輸出到檔案流
ImageIO.write(image,"jpg", out);
// 可以正常實現bmp、png、gif轉jpg
//JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//encoder.encode(image); // JPEG編碼
out.close();
}

}

Java 後端壓縮圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.