本文為原創(chuàng),如需轉(zhuǎn)載,請(qǐng)注明作者和出處,謝謝!
縮放圖像的基本原理是創(chuàng)建一個(gè)目標(biāo)大小的畫布,然后讀取源圖像,并將該圖像繪制這個(gè)畫布上。為了使程序通用,源圖像和縮放后的目標(biāo)圖像應(yīng)用分別使用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參數(shù)表示縮放比例,1至100,當(dāng)然,也可以大于100,那就是放大圖像了。但要注意,放得太大會(huì)失真的。
當(dāng)然,也可以重構(gòu)scaleImage方法,使其可以接收?qǐng)D像文件名,代碼如下:
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);
新浪微博:http://t.sina.com.cn/androidguy 昵稱:李寧_Lining