按比例裁剪图片

来源:互联网 发布:软件残余清理工具 编辑:程序博客网 时间:2024/05/21 14:55

//需要用到的jar包http://download.csdn.net/detail/yflxc/8383297

/**

* 压缩图片
* @param inputDir 图片源文件
* @param width 宽度
* @param height 高度
* @param gp
* @param picName 图片名称
* @return
*/
public static boolean cutImg(File f, int width, int height,
boolean gp, String picName) {
boolean bool = false;
try {
Image img = null;
try {
img = ImageIO.read(f);
} catch (Exception e) {


}
// 判断图片格式是否正确
if (img.getWidth(null) == -1 || img.getWidth(null) < 100
|| img.getHeight(null) < 100) {
System.out
.println(" can't read the img or img size is small !");
} else {
float W = img.getWidth(null);
float H = img.getHeight(null);
float ratio = 0.0f;
if (W > H) {
ratio = (float) (H / width);
} else {
ratio = (float) (W / height);
}
int newWidth = (int) (ratio * width);
int newHeight = (int) (ratio * height);
BufferedImage tag = null;
try {
tag = Thumbnails
.of(f)
.sourceRegion(Positions.CENTER, newWidth, newHeight)
.size(width, height).keepAspectRatio(false)
.asBufferedImage();
} catch (IOException e) {
e.printStackTrace();
}
// 把压缩后的图片转为 二进制码 存入字符串
//File file = File.createTempFile("22222", ".jpg");
File file = new File("f://"+picName);
ImageIO.write(tag,"jpg", file);
}
} catch (IOException ex) {
System.err.println("图片打开失败: " + ex);
bool = false;
} catch (NullPointerException e) {
bool= false;
System.err.println("图片链接获取失败!" + e);
}
return bool;
}
0 0
原创粉丝点击