---
title: "JAVA技术：上传图片的缩放处理"
author: "zc4530"
date: "2009-06-09T23:16:12Z"
tags: []
slug: "java"
draft: false
lastmod: "2009-06-09T23:16:12Z"
id: 405552
url: "https://zc4530.iteye.com/blog/405552"
---

图片上传到服务器后，会根据情况将图片缩小成一个图标，我们可以利用java强大的图形处理功能，对上传的图片进行缩放处理。

下面的程序使用jdk1.4中最新的ImageIO对图片进行读写。使用AffineTransform对图片进行缩放。

import java.io.File;import java.awt.image.BufferedImage;import java.awt.Image;import java.awt.image.AffineTransformOp;import javax.imageio.ImageIO;import java.awt.geom.AffineTransform;public class UploadImg{/*** @param fromdir 图片的原始目录* @param todir 处理后的图片存放目录* @param imgfile 原始图片* @param sysimgfile 处理后的图片文件名前缀**/ ............................ public boolean CreateThumbnail() throws Exception{//ext是图片的格式 gif JPG 或pngString ext="";double Ratio=0.0;File F = new File(fromdir,imgfile);if (!F.isFile())throw new Exception(F+" is not image file error in CreateThumbnail!");//首先判断上传的图片是gif还是JPG ImageIO只能将gif转换为pngif (isJpg(imgfile)){ext="jpg";}else{ext="png"; }File ThF = new File(todir,sysimgfile+"."+ext); BufferedImage Bi = ImageIO.read(F);//假设图片宽 高 最大为120 120Image Itemp = Bi.getScaledInstance (120,120,Bi.SCALE_SMOOTH);if ((Bi.getHeight()>120) || (Bi.getWidth()>120)){if (Bi.getHeight()>Bi.getWidth())Ratio = 120.0/Bi.getHeight();elseRatio = 120.0/Bi.getWidth();}AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(Ratio, Ratio), null);Itemp = op.filter(Bi, null);try {ImageIO.write((BufferedImage)Itemp, ext, ThF);}catch (Exception ex) {throw new Exception(" ImageIo.write error in CreatThum.: "+ex.getMessage()); }return (true);}} 


该程序使用了Java 的AWT，在linux下运行可能报错，有两种解决方式：

(1) jdk1.4以前版本：需要安装 XFree86和XFree86-Xvfb ，加入 export DISPLAY=hostdomain:0.0。 

(2) jdk 1.4以后版本，执行命令java 加入参数-Djava.awt.headless=true，表示这是一个没有键盘 没有显示器的无头服务器，意称机房托管的服务器。