Java对图片按需进行裁剪
- 按照需求对图片进行裁剪
-
例如 原图 2000*600 目标图片 1000*300
/**
* 图片裁剪
*/
public void contextLoads() {
try {
InputStream inputStream = new FileInputStream("D:\\upload\\cp0.jpg");
BufferedImage bufferedImage = ImageIO.read(inputStream);
BufferedImage bf = new BufferedImage(1000,300,BufferedImage.TYPE_INT_BGR); //1000*300需要裁剪的大小
bf.getGraphics().drawImage(bufferedImage,0,0,1000,300,null);
FileOutputStream outImgStream = new FileOutputStream("D:\\upload\\cp01.jpg");
ImageIO.write(bufferedImage, "jpg", outImgStream); //直接存储到本地
//暂时存储为字节流用于上传到服务器,我用的是ftp上传
ByteArrayOutputStream baty = new ByteArrayOutputStream();
ImageIO.write(bf,"jpg",baty);
byte[] buff = baty.toByteArray();
InputStream in = new ByteArrayInputStream(buff); //存储为字节流,用于上传到服务器
FileOutputStream fos = new FileOutputStream("d:\\aa.jpg"); //转换为字节流存储到本地的测试方法,证明转换成功
byte[] b = new byte[1024];
int length;
while((length = in.read(b)) != -1 ){
fos.write(b,0,length);
}
in.close();
fos.close();
}catch (Exception e){
e.printStackTrace();
}
}