本文实例讲述了java生成缩略图的方法。分享给大家供大家参考,具体如下:
package com.util;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* 生成压缩图
*
*/
public class ImageScale {
private int width;
private int height;
private int scaleWidth;
double support = (double) 3.0;
double PI = (double) 3.14159265358978;
double[] contrib;
double[] normContrib;
double[] tmpContrib;
int startContrib, stopContrib;
int nDots;
int nHalfDots;
/**
* Start: Use Lanczos filter to replace the original algorithm for image
* scaling. Lanczos improves quality of the scaled image modify by :blade
*/
public BufferedImage imageZoomOut(BufferedImage srcBufferImage, int w, int h) {
width = srcBufferImage.getWidth();
height = srcBufferImage.getHeight();
scaleWidth = w;
if (DetermineResultSize(w, h) == 1) {
return srcBufferImage;
}
CalContrib();
BufferedImage pbOut = HorizontalFiltering(srcBufferImage, w);
BufferedImage pbFinalOut = VerticalFiltering(pbOut, h);
return pbFinalOut;
}
/**
* 决定图像尺寸
*/
private int DetermineResultSize(int w, int h) {
double scaleH, scaleV;
// update by libra
double wt = w > width ? width : w;
double ht = h > height ? height : h;
scaleH = (double) wt / (double) width;
scaleV = (double) ht / (double) height;
// 需要判断一下scaleH,scaleV,不做放大操作
if (scaleH >= 1.0 && scaleV >= 1.0) {
return 1;
}
return 0;
} // end of DetermineResultSize()
private double Lanczos(int i, int inWidth, int outWidth, double Support) {
double x;
x = (double) i * (double) outWidth / (double) inWidth;
return Math.sin(x * PI) / (x * PI) * Math.sin(x * PI / Support)
/ (x * PI / Support);
} // end of Lanczos()
//
// Assumption: same horizontal and vertical scaling factor
//
private void CalContrib() {
nHalfDots = (int) ((double) width * support / (double) scaleWidth);
nDots = nHalfDots * 2 + 1;
try {
contrib = new double[nDots];
normContrib = new double[nDots];
tmpContrib = new double[nDots];
} catch (Exception e) {
System.out.println("init contrib,normContrib,tmpContrib" + e);
}
int cente