天天看點

java讀取圖檔縮略方法_如何用java壓縮圖檔 生成縮略圖

2014-02-17 06:30:01

閱讀( 56 )

package com.util;

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.JPEGEncodeParam;

import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class PicCompression {

public static String doCompress(String oldFile, int width, int height, float quality, String smallIcon, boolean percentage) {

if (oldFile != null && width > 0 && height > 0) {

String newImage = null;

try {

File file = new File(oldFile);

// 檔案不存在

if (!file.exists()) {

return null;

}

Image srcFile = ImageIO.read(file);

int new_w = width;

int new_h = height;

if (percentage) {

// 為等比縮放計算輸出的圖檔寬度及高度

double rate1 = ((double) srcFile.getWidth(null)) / (double) width + 0.1;

double rate2 = ((double) srcFile.getHeight(null)) / (double) height + 0.1;

double rate = rate1 > rate2 ? rate1 : rate2;

new_w = (int) (((double) srcFile.getWidth(null)) / rate);

new_h = (int) (((double) srcFile.getHeight(null)) / rate);

}

BufferedImage tag = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);

tag.getGraphics().drawImage(srcFile, 0, 0, new_w, new_h, null);

String filePrex = oldFile.substring(0, oldFile.lastIndexOf(‘.’));

newImage = filePrex + smallIcon + oldFile.substring(filePrex.length());

FileOutputStream out = new FileOutputStream(newImage);

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);

jep.setQuality(quality, true);

encoder.encode(tag, jep);

out.close();

srcFile.flush();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return newImage;

} else {

return null;

}

}

//測試

public static void main(String str[]) {

System.out.println(PicCompression.doCompress(“F:/new.bmp”, 80, 50, 1, “_small”, false));

System.out.print(“ok…”);

}

}

分享給朋友:

親~ 如果您有更好的答案 可在評論區發表您獨到的見解。

您想檢視更多的資訊:

面試題