cloud21 发表于 2013-1-15 02:36:37

使用Java等比例缩放图像

缩放图像的基本原理是创建一个目标大小的画布,然后读取源图像,并将该图像绘制这个画布上。为了使程序通用,源图像和缩放后的目标图像应用分别使用 InputStream和OutputStream来表示,代码如下:

public   static   voidscaleImage(InputStream imgInputStream,            OutputStream imgOutputStream,intscale)    {         try         {            Image src=javax.imageio.ImageIO.read(imgInputStream);             intwidth=( int ) (src.getWidth( null )*scale/   100.0 );             intheight=( int ) (src.getHeight( null )*scale/   100.0 );            BufferedImage bufferedImage=   newBufferedImage(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   voidscaleImage(String imgSrc, String imgDist,intscale)    {         try         {            File file=   newFile(imgSrc);             if( ! file.exists())            {               return ;            }            InputStream is=   newFileInputStream(file);            OutputStream os=   newFileOutputStream(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
页: [1]
查看完整版本: 使用Java等比例缩放图像