Java生成缩略图,提高网络请求速度!!!!
简介:
Web应用为上传图片生成缩略图是常见的基本功能,通过缩略图生成提高了信息浏览时的性能,在保证用户使用体验的同时减少了数据传输量。这门课程以实例的方式,讲解如何使用使用Java实现图片等比例缩略图生成功能。
原图:311KB
缩略图:2KB
具体代码如下:
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
/**
* 生成图片缩略图
*
* @author Administrator
*
*/
public class ThumbnailUtil {
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;
public static void main(String[] args) {
ThumbnailUtil is = new ThumbnailUtil();
try {
String imgFrom = "c://1.jpg";
String imgTo = "c://1-1.jpg";
is.saveImageAsJpg(imgFrom, imgTo, 120, 120);
System.out.println("图片生成缩略图成功!!");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param fromFileStr 原图片地址
* @param saveToFileStr 生成缩略图地址
* @param formatWideth 生成图片宽度
* @param formatHeight formatHeight高度
*/
public void saveImageAsJpg(String fromFileStr, String saveToFileStr, int formatWideth, int formatHeight)
throws Exception {
BufferedImage srcImage;
File saveFile = new File(saveToFileStr);
File fromFile = new File(fromFileStr);
srcImage = javax.imageio.ImageIO.read(fromFile); // construct image
int imageWideth = srcImage.getWidth(null);
int imageHeight = srcImage.getHeight(null);
int changeToWideth = 0;
int changeToHeight = 0;
if (imageWideth > 0 && imageHeight > 0) {
// fl