使用Java对图片裁剪是否重要
很重要!!!很重要!!!很重要!!!重要的事情要三次重复,不管你是开发文件服务,还是使用文件服务,都需要考虑要不要对图片进行裁剪。
为什么呢?
- 假设用户要上传一张很大的照片,我们的文件服务器是能储存,但是在网络传输中,一张大图很占网络资源的,一张图片要加载很久才能加载出来,这个时候把本来的大图裁剪成n张小图,那么网络就会先加载一部门的图片,这样用户在浏览的时候就不会要等很久才能看到想看的图片
- 这个时候有些开发者就会说,为什么不限制上传图片的大小呢,为什么你不用图片压缩工具去压缩呢?首先说一下,为什么不限制图片大小,限制图片大小有的时候当然是可行的,比如我就上传一个icon,上传一个二维码,但是如果要上传一张产品效果图,需要细节很清晰,这个时候限制肯定不行;那么图片压缩呢,一样的,本来我需要一张色彩保真的图片,你压缩一下,把我的色阶色温都变了,我还不如不传呢。
Java怎么实现压缩
private static final Integer INIT_X = 0;
private static final Integer INIT_Y = 0;
private static final String FORMAT_NAME = "JPEG";
private static final String DOT = "\\.";
private static final String DOT_OF_FILE = ".";
public static void cutImageOfLocal(String srcPath, Integer limitHeight) {
try {
// 读取源图像
BufferedImage bi = ImageIO.read(new File(srcPath));
// 原图宽度
int srcWidth = bi.getWidth();
// 原图高度
int srcHeight = bi.getHeight();
// 算出图片要切除几份
int count;
if(limitHeight > srcHeight){
count = 1;
} else {
if (srcHeight % limitHeight > 0) {
count = srcHeight / limitHeight + 1;
}else {
count = srcHeight / limitHeight;
}
}
if (count == 1) {
return;
} else {
String[] pathItem = srcPath.split(DOT);
for (int i = 0; i < count; i++) {
int y = INIT_Y + (i * limitHeight);
if (y + limitHeight >= srcHeight) {
limitHeight = srcHeight - y;
}
Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
// 裁剪
ImageFilter cropFilter = new CropImageFilter(INIT_X, y , srcWidth, limitHeight);
// 使用裁剪下的部门创建一张图片
Image img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
BufferedImage tag = new BufferedImage(srcWidth, limitHeight, BufferedImage.TYPE_INT_BGR);
// 用图像的画笔画出图像
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
String descPath = pathItem[0] + (i + 1);
// 写到本地
ImageIO.write(tag, FORMAT_NAME, new File(descPath + DOT_OF_FILE + pathItem[1]));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
上面就是裁剪本地的图片,分为n张
如果是网络资源,那么久要涉及到下载:
/**
* 通过url下载图片
*
* @param srcUrl 网络资源
* @param path 路径
*/
private static void downloadPicture(String srcUrl,String path) {
URL url = null;
try {
url = new URL(srcUrl);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
网友评论