|
缩放图像的基本原理是创建一个目标大小的画布,然后读取源图像,并将该图像绘制这个画布上。为了使程序通用,源图像和缩放后的目标图像应用分别使用InputStream和OutputStream来表示,代码如下:
Code highlighting produced by Actipro CodeHighlighter (freeware) | http://www.CodeHighlighter.com/ | | --> 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方法,使其可以接收图像文件名,代码如下:
Code highlighting produced by Actipro CodeHighlighter (freeware) | http://www.CodeHighlighter.com/ | | --> 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%缩放
Code highlighting produced by Actipro CodeHighlighter (freeware) | http://www.CodeHighlighter.com/ | | -->scaleImage("E:\\pictures\\test.jpg", "e:\\test1.jpg", 15); |
[/td][/tr][/table] |
|