您的位置:首页 > 编程语言 > Java开发

java 图片处理

2016-07-15 18:34 381 查看
用到两个第三方库

1、thumbnailator:https://github.com/coobird/thumbnailator

2、TwelveMonkeys:https://github.com/haraldk/TwelveMonkeys

thumbnailator是图片处理的工具类,提供了很多图片处理的便捷的方法,这样我们就不要用jdk底层的ImageIO类了

TwelveMonkeys是一个图片编解码库,支持bmp,jpeg,tiff,pnm,psd等。jdk本身也支持一些图片的处理,如jpeg,bmp,png,但是jdk的图片编解码库不是很强。

为什么需要TwelveMonkeys?我在处理jpeg图片的时候,发现用jdk自带的jpeg解析器不能解析所有的jpeg格式文件(部分Photoshop处理过的jpeg图片)。出现unsupported formate 错误,用这个库后,没有出现错误。

thumbnailator的功能有按比例缩放,固定尺寸缩放,按尺寸等比缩放,旋转,加水印,压缩图片质量。thumbnailator固定尺寸缩放有可能会造成图片变型,有的时候我们可能需要固定尺寸并等比缩放,不够的地方补上空白。它没有提供直接的功能。下面是自己写的代码

public static void compressByPx(InputStream inputStream, OutputStream outputStream,int width, int height, boolean equalProportion) throws IOException {
BufferedImage bufferedImage=ImageIO.read(inputStream);
int sWidth=bufferedImage.getWidth();
int sHeight=bufferedImage.getHeight();
int diffWidth=0;
int diffHeight=0;
if(equalProportion){
if((double)sWidth/width>(double)sHeight/height){
int height2=width*sHeight/sWidth;
diffHeight=(height-height2)/2;
}else if((double)sWidth/width<(double)sHeight/height){
int width2=height*sWidth/sHeight;
diffWidth=(width-width2)/2;
}
}
BufferedImage nbufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
nbufferedImage.getGraphics().fillRect(0,0,width,height);//填充整个屏幕
nbufferedImage.getGraphics().drawImage(bufferedImage, diffWidth, diffHeight, width-diffWidth*2, height-diffHeight*2, null); // 绘制缩小后的图
ImageIO.write(nbufferedImage,"jpg",outputStream);
outputStream.close();
inputStream.close();
}

equalProportion代表是否等比例缩放,如果是则等比缩放,并在不够的地方留白

一个1024x674的源图片,现在要生成一个800x800的图片

源文件



Thumbnails.of(new File("e:/x/1.jpg"))
.size(800, 800)
.toFile(new File("e:/x/thumbnail/1.jpg"));使用size方法生成的图片



这个图片没有变型,但他的实际像素并不是800x800,而是800x527.

Thumbnails.of(new File("e:/x/1.jpg"))
.forceSize(800, 800)
.toFile(new File("e:/x/thumbnail/1.jpg"));

使用forceSize方法生成的图片



这张图片的实际像素是800x800

try {
compressByPx(new FileInputStream("E:/x/1.jpg"),new FileOutputStream("E:/x/thumbnail/1.jpg"),800,800,true);
} catch (IOException e) {
e.printStackTrace();
}使用自己写的compressByPx方法产生的图片



这张图片的实际像素是800x800,也没有产生变型,而是在上部分和下部分留白了一块。大家根据实际情况的需要选择使用哪个方法。

TwelveMonkeys的使用比较简单,只要把相关的jar包加入到类路径,他的类我们基本不会用到,只要使用jdk ImageIO或其上层的接口就行了。jdk的ImageIO有自动发现功能,会自动查找相关的编解码类并使用,而不使用jdk默认的编解码类,所以使用这个库是完全无入侵的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息