全栈工程师开发手册 (作者:栾鹏)
java实现图片裁剪,输入起点x、y,宽度width、高度height
测试代码
public static void main(String[] args) {
//文件与BufferedImage间的转换
BufferedImage bi=file2img("test.jpg"); //读取图片
BufferedImage bii=img_tailor(bi,50,50,50,50);
img2file(bii,"jpg","test1.jpg"); //生成图片
}
裁剪函数的实现
public static BufferedImage img_tailor(BufferedImage src,int x,int y,int width,int height) {
BufferedImage back=src.getSubimage(x,y,width,height);
return back;
}
图片的读取和存储
//读取图片
public static BufferedImage file2img(String imgpath) {
try {
BufferedImage bufferedImage=ImageIO.read(new File(imgpath));
return bufferedImage;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//保存图片,extent为格式,"jpg"、"png"等
public static void img2file(BufferedImage img,String extent,String newfile) {
try {
ImageIO.write(img, extent, new File(newfile));
} catch (Exception e) {
e.printStackTrace();
}
}