小伙伴们,在做项目中,我们常常会使用工具类减轻我们的代码量,让我们的项目更加的清晰明了!
1、外部获取图片工具类 ImageUtils.java
完整代码:
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
public class ImageUtil {
/**
* 根据路径加载图片
* @param path
* @return
*/
public static Image getImageByLocalFilePath(String path){
//获取图片
Image result = null;
FileInputStream fis = null;
//获取输入流
try {
fis = new FileInputStream(path);
//读取输入路径
try {
result = ImageIO.read(fis);
} catch (IOException e) {
e.printStackTrace();
return null;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}finally {
if(fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
public static Image getImageByURLPath(String urlPath) {
//获取图片
Image result = null;
URL url = null;
try {
url = new URL(urlPath);
result = ImageIO.read(url);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
return result;
}
/**
* 设定图片的大小
* @return
*/
public static Image getScalImage(Image img,int width,int height) {
//过滤非法
if(img == null || width == 0 || height == 0 ) {
System.out.println("参数不正确!");
return null;
}
//获取图片的长和宽
int imgWidth = img.getWidth(null);
int imgheight = img