java 图片处理

http://blog.csdn.net/fengwind1/article/details/51919848git

********************************************************github

用到两个第三方库工具

一、thumbnailator:https://github.com/coobird/thumbnailatorspa

二、TwelveMonkeys:https://github.com/haraldk/TwelveMonkeys.net

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

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

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

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

    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默认的编解码类,因此使用这个库是彻底无入侵的

相关文章
相关标签/搜索