六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 54|回复: 0

使用Java等比例缩放图像

[复制链接]

升级  51.33%

33

主题

33

主题

33

主题

秀才

Rank: 2

积分
127
 楼主| 发表于 2013-1-15 02:36:37 | 显示全部楼层 |阅读模式
缩放图像的基本原理是创建一个目标大小的画布,然后读取源图像,并将该图像绘制这个画布上。为了使程序通用,源图像和缩放后的目标图像应用分别使用 InputStream和OutputStream来表示,代码如下:

public   static   void  scaleImage(InputStream imgInputStream,            OutputStream imgOutputStream,  int  scale)    {         try         {            Image src  =  javax.imageio.ImageIO.read(imgInputStream);             int  width  =  ( int ) (src.getWidth( null )  *  scale  /   100.0 );             int  height  =  ( int ) (src.getHeight( null )  *  scale  /   100.0 );            BufferedImage bufferedImage  =   new  BufferedImage(width, height,                    BufferedImage.TYPE_INT_RGB);             bufferedImage.getGraphics().drawImage(                    src.getScaledInstance(width, height, Image.SCALE_SMOOTH),                     0 ,  0 ,  null );            JPEGImageEncoder encoder  =  JPEGCodec                    .createJPEGEncoder(imgOutputStream);            encoder.encode( bufferedImage);        }         catch  (IOException e)        {            e.printStackTrace();        }    }

其中scale参数表示缩放比例,1至100,当然,也可以大于100,那就是放大图像了。但要注意,放得太大会失真的。
    当然,也可以重构scaleImage方法,使其可以接收图像文件名,代码如下:

public   static   void  scaleImage(String imgSrc, String imgDist,  int  scale)    {         try         {            File file  =   new  File(imgSrc);             if  ( ! file.exists())            {                 return ;            }            InputStream is  =   new  FileInputStream(file);            OutputStream os  =   new  FileOutputStream(imgDist);            scaleImage(is, os, scale);            is.close();            os.close();        }         catch  (Exception e)        {        }    }  

下面的代码按15%缩放
scaleImage( " E:\\pictures\\test.jpg " ,  " e:\\test1.jpg " ,  15 );
本文来自CSDN博客:http://blog.csdn.net/nokiaguy/archive/2010/04/16/5493817.aspx
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表