图片缩放
程序员文章站
2024-03-24 12:24:22
...
/**
*
* 功能描述:缩放并上传图片(使用Java提供的ImageIO简单处理)
*
* @param 源图片输入流 ins
* @param 目标图片输出流 os
* @param 宽
* :如果为null则按高度等比例
* @param 高
* :如果为null则按宽度等比例
* @param 图片后缀名
* (png/jpg)
* @throws IOException
*/
private void Compressed image(InputStream ins, OutputStream os, Integer width,
Integer height, String suffix) throws IOException
{
try
{
// 读取原图
BufferedImage src = ImageIO.read(ins);
// 源图宽高
int sw = src.getWidth();
int sh = src.getHeight();
// 新图宽高
if (width == null || width <= 0)
{
if (height == null || height <= 0)
{
width = sw;
height = sh;
}
else
{
//压缩宽度
width = (sw / sh) * height;
}
}
else
{
if (height == null || height <= 0)
{
//高度压缩
height = (sh / sw) * width;
}
}
// 新图
BufferedImage newImg = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 绘制:x起点,y起点,宽,高
newImg.getGraphics().drawImage(src, 0, 0, width, height, null);
// 输出:新图,格式(png/jpg),输出流
ImageIO.write(newImg, suffix, os);
// 释放资源
os.flush();
os.close();
}
catch (Exception e)
{
e.printStackTrace();
throw new IOException("上传图片失败:读取或缩放失败");
}
}
/**
* 获取图片宽度
*
* @param file
* 图片文件
* @return 宽度
*/
public static int[] getImgWidth(File file) {
InputStream is = null;
BufferedImage src = null;
int imageSize[] = { 0, 0 };
try {
is = new FileInputStream(file);
src = javax.imageio.ImageIO.read(is);
imageSize[0] = src.getWidth(null); // 得到源图宽
imageSize[1] = src.getHeight(null); // 得到源图高
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return imageSize;
}
测试:
public static void main(String[] args) throws FileNotFoundException,
IOException
{
new UploadServiceImpl().zoomUseJava(
new FileInputStream("D:\\timg.jpg"), new FileOutputStream(
"D:\\timg1.jpg"), 1000, 1000, "jpg");
File file = new File("D:\\timg.jpg");
System.out.println(file.length());
File file1 = new File("D:\\timg1.jpg");
System.out.println(file1.length());
}
上一篇: tooltip