Posted on 2007-12-03 23:20
qurui 阅读(103)
评论(0) 编辑 收藏 所属分类:
Java
最近做手机页面,因为手机的缓存很小,需要图片显示时,要将图片的大小进行调整。所以研究了一下,查了些
文章,以这个http://www.webjx.com/htmldata/2005-04-25/1114436950.html为基础进行了一些修改可以自定义大小。
下面是代码:
1 import java.io.File;
2 import java.io.FileOutputStream;
3 import java.awt.Image;
4 import java.awt.image.BufferedImage;
5 import com.sun.image.codec.jpeg.JPEGCodec;
6 import com.sun.image.codec.jpeg.JPEGImageEncoder;
7
8 public class MakeBreviaryImage {
9
10 public void MakeBreviaryImage(File image, int formatWideth,
11 int formatHeight, String savePath) throws Exception {
12 File _file = image;// get image file
13 Image src = javax.imageio.ImageIO.read(_file); // construct image
14 int imageWideth = src.getWidth(null); // get wideth of image
15 int imageHeight = src.getHeight(null); // get height of image
16 int changeToWideth = 0;
17 int changeToHeight = 0;
18 // set Breviary image's size
19 if (imageWideth > 0 && imageHeight > 0) {
20 // flag=true;
21 if (imageWideth / imageHeight >= formatWideth / formatHeight) {
22 if (imageWideth > formatWideth) {
23 changeToWideth = formatWideth;
24 changeToHeight = (imageHeight * formatWideth) / imageWideth;
25 } else {
26 changeToWideth = imageWideth;
27 changeToHeight = imageHeight;
28 }
29 } else {
30 if (imageHeight > formatHeight) {
31 changeToHeight = formatHeight;
32 changeToWideth = (imageWideth * formatHeight) / imageHeight;
33 } else {
34 changeToWideth = imageWideth;
35 changeToHeight = imageHeight;
36 }
37 }
38 }
39 // ---------
40 BufferedImage bufferedImage = new BufferedImage(changeToWideth,
41 changeToHeight, BufferedImage.TYPE_INT_RGB);
42 bufferedImage.getGraphics().drawImage(src, 0, 0, changeToWideth,
43 changeToHeight, null); // chage image size
44 FileOutputStream out = new FileOutputStream(savePath); // out put the
45 // image
46 JPEGImageEncoder encoder = null;
47 encoder = JPEGCodec.createJPEGEncoder(out);
48 encoder.encode(bufferedImage); // like JPEG encoding
49 // System.out.print(width+"*"+height);
50 out.close();
51 }
52 }
我把上面的代码封装成一个类。
调用时
1 public class TestMakeBreviaryImage {
2
3 /**
4 * @param args
5 * @throws Exception
6 */
7 public static void main(String[] args) throws Exception {
8 File testImage = new File("C:\\Documents and Settings\\All Users\\Documents\\My Pictures\\Sample Pictures\\nuclear-test-7.jpg");
9 MakeBreviaryImage test = new MakeBreviaryImage();
10 test.MakeBreviaryImage(testImage,60,50,"C:/newfile.jpg");
11 }
12
13 }