圖片剪裁實現

圖片剪裁實現:
if (fileName.indexOf("HEIGHT") != -1) {
                        
                        ByteArrayOutputStream bOutPutStream=new ByteArrayOutputStream();
                        ImageTools.scaleByHeight(f.getInputStream(), fileName,
                                bOutPutStream);
                        if(bOutPutStream.size()<1){
                            response.setContentLength(Integer.valueOf(f.getLength()+""));
                        }else{
                            response.setContentLength(bOutPutStream.size());
                        }
                        response.getOutputStream().write(bOutPutStream.toByteArray());
                        
                        //ImageTools.scaleByHeight(f.getInputStream(), fileName,
                        //        response.getOutputStream());
                        
                    }

1.圖片剪裁工具類:
下載包:http://mvnrepository.com/search?q=net.coobird
thumbnailator-0.4.7.jar
log4j-1.2.14.jar
或者在pom.xml增長:
<!-- 裁剪圖片工具 -->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.7</version>
        </dependency>
        <!-- log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.14</version>
        </dependency>



package com.taopl.test;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;

import org.apache.log4j.Logger;


import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

public class ImageTools {
    
    private static Logger logger = Logger.getLogger(ImageTools.class);

    /**
     * 指定大小進行縮放   縮放到至少長寬都比要求的大
     * <desc>
     *  1.size(200,300) 若圖片橫比200小,高比300小,不變
     *  2.若圖片橫比200小,高比300大,高縮小到300,圖片比例不變 若圖片橫比200大,高比300小,橫縮小到200,圖片比例不變
     *  3.若圖片橫比200大,高比300大,圖片按比例縮小,橫爲200或高爲300
     * <desc>
     * @param File
     * @param width 圖片寬
     * @param height 圖片高
     * @param targetPath 要存放圖片的路徑
     * @throws IOException
     * @return 成功返回圖片存放路徑
     */
    public static void scaleBySize(InputStream inputStream,String fileName,ServletOutputStream out) throws IOException {
        //獲取圖片的原長、寬  ssss*400x200.jpg
        String str = "";
        if(fileName.indexOf("*")!=-1){
            str = fileName.substring(fileName.indexOf("*")+1,fileName.indexOf("_"));
        }else{
            String subFileName=fileName.substring(fileName.indexOf("_")+1,fileName.length());
            str = subFileName.substring(0,subFileName.indexOf("_"));
        }
        String endTag = fileName.substring(fileName.lastIndexOf(".")+1);   //後綴
        if(str.indexOf("x")!=-1){
            String[] oldSizes = str.split("x");
            Pattern pattern = Pattern.compile("[0-9]*");
            boolean isNum = pattern.matcher(oldSizes[0]).matches()&&pattern.matcher(oldSizes[1]).matches();  //都是數字
            if(isNum){
                int oldWidth = Integer.parseInt(oldSizes[0]);   //原圖寬
                int oldHeight = Integer.parseInt(oldSizes[1]);  //原圖高
                String newSize = fileName.substring(fileName.lastIndexOf("_")+1,fileName.lastIndexOf("."));//縮放要求的尺寸
                String[] newSizes = newSize.split("x");
                isNum = pattern.matcher(newSizes[0]).matches()&&pattern.matcher(newSizes[1]).matches();
                if(isNum){
                    int newWidth = Integer.parseInt(newSizes[0]);   //要求要壓縮的寬
                    int newHeight = Integer.parseInt(newSizes[1]);  //要求要壓縮的高
                    float wRatio =  Float.valueOf(oldWidth) /Float.valueOf(newWidth);
                    float hRatio =  Float.valueOf(oldHeight) /Float.valueOf(newHeight);
                    //計算假設等比壓縮後能不能達到兩邊都不小於要求的長寬
                    if(oldWidth<newWidth&&oldHeight<newHeight){
                        //按照指定大小縮放
                        //Thumbnails.of(inputStream).size(newWidth, newHeight).keepAspectRatio(false).outputFormat(endTag).toOutputStream(out);
                        
                        //根據短邊放大再裁剪
                        if(wRatio<hRatio){  //對比原圖的寬大仍是高大。由於要按大邊等比壓縮
                            int targetWidth=(int)(oldHeight/wRatio);
                            BufferedImage bufferedImage =  Thumbnails.of(inputStream).size(newWidth,targetWidth ).keepAspectRatio(false).asBufferedImage();//等比壓縮
                            Thumbnails.of(bufferedImage).sourceRegion(Positions.CENTER, newWidth,     
                                    newHeight).size(newWidth, newHeight).outputFormat(endTag).toOutputStream(out);
                        }else{
                            int targetHeight=(int)(oldWidth/hRatio);
                            BufferedImage bufferedImage =  Thumbnails.of(inputStream).size(targetHeight, newHeight).keepAspectRatio(false).asBufferedImage();//等比壓縮
                            Thumbnails.of(bufferedImage).sourceRegion(Positions.CENTER, newWidth,     
                                    newHeight).size(newWidth, newHeight).outputFormat(endTag).toOutputStream(out);
                        }
                        
                        
                        //原圖出去
                        //Thumbnails.of(inputStream).size(oldWidth, oldHeight).outputFormat(endTag).toOutputStream(out);
                    }else if(oldWidth<newWidth){
                        //按照指定大小縮放
                        //Thumbnails.of(inputStream).size(newWidth, newHeight).keepAspectRatio(false).outputFormat(endTag).toOutputStream(out);
                        
                        //根據短邊放大再裁剪
                        int targetWidth=(int)(oldHeight/wRatio);
                        BufferedImage bufferedImage =  Thumbnails.of(inputStream).size(newWidth,targetWidth ).keepAspectRatio(false).asBufferedImage();//等比壓縮
                        Thumbnails.of(bufferedImage).sourceRegion(Positions.CENTER, newWidth,     
                                newHeight).size(newWidth, newHeight).outputFormat(endTag).toOutputStream(out);
                        
                        
                        //若是原圖寬小了 ,則根據高裁剪出去
                        //Thumbnails.of(inputStream).sourceRegion(Positions.CENTER, oldWidth,     
                        //        newHeight).size(oldWidth,newHeight).outputFormat(endTag).toOutputStream(out);
                    }else if(oldHeight<newHeight){
                        //按照指定大小縮放
                        //Thumbnails.of(inputStream).size(newWidth, newHeight).keepAspectRatio(false).outputFormat(endTag).toOutputStream(out);
                        
                        int targetHeight=(int)(oldWidth/hRatio);
                        BufferedImage bufferedImage =  Thumbnails.of(inputStream).size(targetHeight, newHeight).keepAspectRatio(false).asBufferedImage();//等比壓縮
                        Thumbnails.of(bufferedImage).sourceRegion(Positions.CENTER, newWidth,     
                                newHeight).size(newWidth, newHeight).outputFormat(endTag).toOutputStream(out);
                        
                        //若是原圖高小了 ,則根據寬裁剪出去   
                        //Thumbnails.of(inputStream).sourceRegion(Positions.CENTER, newWidth,     
                        //        oldHeight).size(newWidth,oldHeight).outputFormat(endTag).toOutputStream(out);
                        //Thumbnails.of(inputStream).size(oldWidth,oldHeight).outputFormat(endTag).toOutputStream(out);
                    }else{//原圖寬高都比要求的圖片大
                        
                        //float wRatio =  new BigDecimal(oldWidth / newWidth).setScale(10, BigDecimal.ROUND_HALF_UP).floatValue();  //若是按寬比壓縮的壓縮比
                        //float hRatio = new BigDecimal(oldHeight / newHeight).setScale(10, BigDecimal.ROUND_HALF_UP).floatValue();//若是按高等比壓縮的壓縮比
                        if(wRatio<hRatio){  //對比原圖的寬大仍是高大。由於要按大邊等比壓縮
                            //被壓縮後的比例寬小,則按照寬進行壓縮
                            BufferedImage bufferedImage =  Thumbnails.of(inputStream).size(newWidth, newWidth*2).asBufferedImage();//等比壓縮
                            Thumbnails.of(bufferedImage).sourceRegion(Positions.CENTER, newWidth,     
                                    newHeight).size(newWidth, newHeight).outputFormat(endTag).toOutputStream(out);
                            /**
                            
                            //按寬等比壓縮,則計算高等比壓縮出來是否小於要求的高
                            int hPredict = (int)Math.ceil((new BigDecimal(newHeight / wRatio).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue()));  //預計出來的高
                            if(hPredict<newHeight){
                                //若是寬壓到目標高的比例
                                float temp = new BigDecimal(oldWidth / newHeight).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
                                int tarWidth = (int)((float)newHeight*temp+0.1);
                                //按從新計算的等比壓縮要求的寬進行縮放再裁剪,而不是按原目標等比壓縮裁剪
                                BufferedImage bufferedImage =  Thumbnails.of(inputStream).size(tarWidth, newHeight).asBufferedImage();//等比壓縮
                                Thumbnails.of(bufferedImage).sourceRegion(Positions.CENTER, newWidth,     
                                        newHeight).size(newWidth, newHeight).outputFormat(endTag).toOutputStream(out);
                            }else{//按寬等比壓縮後預計高等比壓也不小於要求的高,則按原參數等比壓縮再裁剪
                                BufferedImage bufferedImage =  Thumbnails.of(inputStream).size(newWidth, oldHeight).asBufferedImage();
                                Thumbnails.of(bufferedImage).sourceRegion(Positions.CENTER, newWidth,     
                                        newHeight).size(newWidth, newHeight).outputFormat(endTag).toOutputStream(out);
                            }*/
                        }else{
                            //被壓縮後的比例寬大,則按照高進行壓縮
                            BufferedImage bufferedImage =  Thumbnails.of(inputStream).size(newHeight*2, newHeight).asBufferedImage();//等比壓縮
                            Thumbnails.of(bufferedImage).sourceRegion(Positions.CENTER, newWidth,     
                                    newHeight).size(newWidth, newHeight).outputFormat(endTag).toOutputStream(out);
                            
                            /**
                            //按高等比壓縮,則計算寬等比壓縮出來是否小於要求的寬
                            int wPredict = (int)Math.ceil((new BigDecimal(newWidth / hRatio).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue()));  //預計出來的寬
                            if(wPredict<newWidth){
                                //若是高壓到目標寬的比例
                                float temp = new BigDecimal(oldHeight / newWidth).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
                                int tarHeight = (int)((float)newWidth*temp+0.1);
                                BufferedImage bufferedImage =  Thumbnails.of(inputStream).size(newWidth, tarHeight).asBufferedImage();//等比壓縮
                                Thumbnails.of(bufferedImage).sourceRegion(Positions.CENTER, newWidth,     
                                        newHeight).size(newWidth, newHeight).outputFormat(endTag).toOutputStream(out);
                            }else{
                                BufferedImage bufferedImage =  Thumbnails.of(inputStream).size(newWidth, newHeight).asBufferedImage();
                                Thumbnails.of(bufferedImage).sourceRegion(Positions.CENTER, newWidth,     
                                        newHeight).size(newWidth, newHeight).outputFormat(endTag).toOutputStream(out);
                            }*/
                            
                        }
                    }
                }
            }
        }else{
            logger.error("ERROR:獲取原圖片長寬失敗!");
        }
    }
    
    
    /**
     * 指定固定高度進行縮放
     * @param inputStream
     * @param fileName
     * @param out
     * @throws IOException
     */
    public static void scaleByHeight(InputStream inputStream,String fileName,OutputStream out) throws IOException {
        //獲取圖片的原長、寬  ssss*400x200.jpg
        String str = "";
        if(fileName.indexOf("*")!=-1){
            str = fileName.substring(fileName.indexOf("*")+1,fileName.indexOf("_"));
        }else{
            String subFileName=fileName.substring(fileName.indexOf("_")+1,fileName.length());
            str = subFileName.substring(0,subFileName.indexOf("_"));
        }
        String endTag = fileName.substring(fileName.lastIndexOf(".")+1);   //後綴
        if(str.indexOf("x")!=-1){
            String[] oldSizes = str.split("x");
            Pattern pattern = Pattern.compile("[0-9]*");
            boolean isNum = pattern.matcher(oldSizes[0]).matches()&&pattern.matcher(oldSizes[1]).matches();  //都是數字
            if(isNum){
                int oldWidth = Integer.parseInt(oldSizes[0]);   //原圖寬
                int oldHeight = Integer.parseInt(oldSizes[1]);  //原圖高
                String newSize = fileName.substring(fileName.lastIndexOf("_")+1,fileName.lastIndexOf("."));//縮放要求的尺寸
                String[] newSizes = newSize.split("x");
                isNum = pattern.matcher(newSizes[0]).matches()&&pattern.matcher(newSizes[1]).matches();
                if(isNum){
                    int newWidth = Integer.parseInt(newSizes[0]);   //要求要壓縮的寬
                    int newHeight = Integer.parseInt(newSizes[1]);  //要求要壓縮的高
                    float wRatio =  Float.valueOf(oldWidth) /Float.valueOf(newWidth);
                    float hRatio =  Float.valueOf(oldHeight) /Float.valueOf(newHeight);
                    //計算假設等比壓縮後能不能達到兩邊都不小於要求的長寬
                    if(oldHeight<newHeight){
                        //按照指定高縮放
                        
                        int targetHeight=(int)(oldWidth/hRatio);
                        Thumbnails.of(inputStream).size(targetHeight, newHeight).keepAspectRatio(false).outputFormat(endTag).toOutputStream(out);//等比壓縮
                    }else{//原圖高比要求圖片大
                        //按照高進行壓縮
                        Thumbnails.of(inputStream).size(newHeight*2, newHeight).outputFormat(endTag).toOutputStream(out);
                    }
                }
            }
        }else{
            logger.error("ERROR:獲取原圖片長寬失敗!");
        }
    }
    
    /**
     * 指定固定寬度進行縮放
     * @param inputStream
     * @param fileName
     * @param out
     * @throws IOException
     */
    public static void scaleByLength(InputStream inputStream,String fileName,OutputStream out) throws IOException {
        //獲取圖片的原長、寬  ssss*400x200.jpg
        String str = "";
        if(fileName.indexOf("*")!=-1){
            str = fileName.substring(fileName.indexOf("*")+1,fileName.indexOf("_"));
        }else{
            String subFileName=fileName.substring(fileName.indexOf("_")+1,fileName.length());
            str = subFileName.substring(0,subFileName.indexOf("_"));
        }
        String endTag = fileName.substring(fileName.lastIndexOf(".")+1);   //後綴
        if(str.indexOf("x")!=-1){
            String[] oldSizes = str.split("x");
            Pattern pattern = Pattern.compile("[0-9]*");
            boolean isNum = pattern.matcher(oldSizes[0]).matches()&&pattern.matcher(oldSizes[1]).matches();  //都是數字
            if(isNum){
                int oldWidth = Integer.parseInt(oldSizes[0]);   //原圖寬
                int oldHeight = Integer.parseInt(oldSizes[1]);  //原圖高
                String newSize = fileName.substring(fileName.lastIndexOf("_")+1,fileName.lastIndexOf("."));//縮放要求的尺寸
                String[] newSizes = newSize.split("x");
                isNum = pattern.matcher(newSizes[0]).matches()&&pattern.matcher(newSizes[1]).matches();
                if(isNum){
                    int newWidth = Integer.parseInt(newSizes[0]);   //要求要壓縮的寬
                    int newHeight = Integer.parseInt(newSizes[1]);  //要求要壓縮的高
                    float wRatio =  Float.valueOf(oldWidth) /Float.valueOf(newWidth);
                    float hRatio =  Float.valueOf(oldHeight) /Float.valueOf(newHeight);
                    //原圖寬度比目標小
                    if(oldWidth<newWidth){
                        //根據寬放大輸出
                        int targetWidth=(int)(oldHeight/wRatio);
                        Thumbnails.of(inputStream).size(newWidth,targetWidth ).keepAspectRatio(false).outputFormat(endTag).toOutputStream(out);
                    }else{//原圖寬都比要求的圖片大
                        //則按照寬進行壓縮
                        Thumbnails.of(inputStream).size(newWidth, newWidth*2).outputFormat(endTag).toOutputStream(out);//等比壓縮
                    }
                }
            }
        }else{
            logger.error("ERROR:獲取原圖片長寬失敗!");
        }
    }
    
    
    public static void scaleByHeight_bank(InputStream inputStream,String fileName,OutputStream os) throws IOException {
        //獲取圖片的原長、寬
        //String str = fileName.substring(fileName.indexOf("*")+1,fileName.indexOf("_"));
        
        String str = "";
        if(fileName.indexOf("*")!=-1){
            str = fileName.substring(fileName.indexOf("*")+1,fileName.indexOf("_"));
        }else{
            String subFileName=fileName.substring(fileName.indexOf("_")+1,fileName.length());
            str = subFileName.substring(0,subFileName.indexOf("_"));
        }
        
        String endTag = fileName.substring(fileName.lastIndexOf(".")+1);
        if(str.indexOf("x")!=-1){
            String[] oldSizes = str.split("x");
            Pattern pattern = Pattern.compile("[0-9]*");
            boolean isNum = pattern.matcher(oldSizes[0]).matches()&&pattern.matcher(oldSizes[1]).matches();  //都是數字
            if(isNum){
                int oldWidth = Integer.parseInt(oldSizes[0]);   //原圖寬
                int oldHeight = Integer.parseInt(oldSizes[1]);  //原圖高
                String newSize = fileName.substring(fileName.lastIndexOf("_")+1,fileName.lastIndexOf("."));//縮放要求的尺寸
                String[] newSizes = newSize.split("x");
                isNum = pattern.matcher(newSizes[0]).matches()&&pattern.matcher(newSizes[1]).matches();
                if(isNum){
                    int newWidth = Integer.parseInt(newSizes[0]);   //要求要壓縮的寬
                    int newHeight = Integer.parseInt(newSizes[1]);  //要求要壓縮的高
                    if(oldHeight<newHeight){  //若是原圖高小於要求的高
                        Thumbnails.of(inputStream).outputFormat(endTag).toOutputStream(os);
                    }else{
                        float hRatio = new BigDecimal(oldHeight / newHeight).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();//若是按高等比壓縮的壓縮比
                        int wPredict = (int)Math.ceil((new BigDecimal(oldWidth / hRatio).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue()));  //預計出來的寬
                        Thumbnails.of(inputStream).size(wPredict,newHeight).outputFormat(endTag).toOutputStream(os);
                    }
                }
                
            }
        }
        
        
        //Thumbnails.of(inputStream).size(w, h).outputFormat(endTag).toOutputStream(os);
    }
    
    /**
     * 指定大小進行縮放
     * <desc>
     *  1.size(200,300) 若圖片橫比200小,高比300小,不變
     *  2.若圖片橫比200小,高比300大,高縮小到300,圖片比例不變 若圖片橫比200大,高比300小,橫縮小到200,圖片比例不變
     *  3.若圖片橫比200大,高比300大,圖片按比例縮小,橫爲200或高爲300
     * <desc>
     * @param File
     * @param width 圖片寬
     * @param height 圖片高
     * @param targetPath 要存放圖片的路徑
     * @throws IOException
     * @return 成功返回圖片存放路徑
     */
    public static void scaleBySize(BufferedImage bufferedImage,String fileName,int w,int h,OutputStream os) throws IOException {
        String endTag = fileName.substring(fileName.lastIndexOf(".")+1);
        Thumbnails.of(bufferedImage).size(w, h).outputFormat(endTag).toOutputStream(os);
    }
    
    public static void scaleBySize(InputStream in,String fileName,OutputStream os) throws IOException {
        String sizes = fileName.substring(fileName.lastIndexOf("_")+1,fileName.lastIndexOf("."));
        String[] wh = sizes.split("x");
        Thumbnails.of(in).size(Integer.parseInt(wh[0]), Integer.parseInt(wh[1])).toOutputStream(os);
    }
    
    /**
     * 指定大小進行縮放
     * <desc>
     *  1.size(200,300) 若圖片橫比200小,高比300小,不變
     *  2.若圖片橫比200小,高比300大,高縮小到300,圖片比例不變 若圖片橫比200大,高比300小,橫縮小到200,圖片比例不變
     *  3.若圖片橫比200大,高比300大,圖片按比例縮小,橫爲200或高爲300
     * <desc>
     * @param File
     * @param width 圖片寬
     * @param height 圖片高
     * @param targetPath 要存放圖片的路徑
     * @throws IOException
     * @return 成功返回圖片存放路徑
     */
    public static void scaleBySize(InputStream inputStream,String fileName,int w,int h,OutputStream os) throws IOException {
        String endTag = fileName.substring(fileName.lastIndexOf(".")+1);
        Thumbnails.of(inputStream).size(w, h).outputFormat(endTag).toOutputStream(os);
    }
    
    
    
    /**
     * 指定大小進行縮放
     * <desc>
     *  1.size(200,300) 若圖片橫比200小,高比300小,不變
     *  2.若圖片橫比200小,高比300大,高縮小到300,圖片比例不變 若圖片橫比200大,高比300小,橫縮小到200,圖片比例不變
     *  3.若圖片橫比200大,高比300大,圖片按比例縮小,橫爲200或高爲300
     * <desc>
     * @param File
     * @param width 圖片寬
     * @param height 圖片高
     * @param targetPath 要存放圖片的路徑
     * @throws IOException
     * @return 成功返回圖片存放路徑
     */
    public static String scaleBySize(File file,int width,int height,String targetPath) throws IOException {
        try {
            String filename = file.getName();
            String endTag = filename.substring(filename.lastIndexOf(".")+1);
            String path = targetPath+"/"+filename+"_"+width+"x"+height+"."+endTag;
            Thumbnails.of(file).size(width, height).toFile(path);
            return path;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }
    
    /**
     * 按照比例進行縮放
     * @param File
     * @param float 縮放的比例
     * @param targetPath 要存放圖片的路徑
     * @throws IOException
     * @return 成功返回圖片存放路徑
     */
    public static String scaleByRatio (File file,float ratiof,String targetPath) throws IOException {
        try {
            String filename = file.getName();
            String endTag = filename.substring(filename.lastIndexOf(".")+1);
            String path = targetPath+"/"+filename+"_"+(ratiof*100)+"."+endTag;
            Thumbnails.of(file).scale(0.25f).toFile(path);
            return path;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 不按照比例,指定大小進行縮放(圖片可能會變形)
     * @param File
     * @param width 圖片寬
     * @param height 圖片高
     * @param targetPath 要存放圖片的路徑
     * @throws IOException
     * @return 成功返回圖片存放路徑
     */
    public static String scaleByNoRatio(File file,int width,int height,String targetPath) throws IOException {
        try {
            String filename = file.getName();
            String endTag = filename.substring(filename.lastIndexOf(".")+1);
            String path = targetPath+"/"+filename+"_"+width+"x"+height+"."+endTag;
            Thumbnails.of(file).size(120, 120).keepAspectRatio(false).toFile(path);
            return path;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 旋轉圖片
     * @param File
     * @param rotate(角度),正數:順時針, 負數:逆時針
     * @param targetPath 要存放圖片的路徑
     * @throws IOException
     * @return 成功返回圖片存放路徑
     */
    public static String rotate(File file,int rotate,String targetPath) throws IOException {
        try {
            String filename = file.getName();
            String endTag = filename.substring(filename.lastIndexOf(".")+1);
            String path = "";
            if(rotate<0){
                path = targetPath+"/"+filename+"_"+"-"+rotate+"."+endTag;
            }else{
                path = targetPath+"/"+filename+"_"+"+"+rotate+"."+endTag;
            }
            Thumbnails.of(file).size(1280, 1024).rotate(rotate).toFile(path);
            return path;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 水印(位置,水印圖,透明度)
     * @param File file 要設置的圖片
     * @param File mark 水印圖
     * @param 要設置的位置  默認"CENTER"(可傳:"CENTER","CENTER_LEFT","CENTER_RIGHT","TOP_CENTER","TOP_LEFT","TOP_RIGHT","BOTTOM_CENTER","BOTTOM_LEFT","BOTTOM_RIGHT")
     * @param Float quality1f 傳入圖片的透明度(質量,如0.5f,默認0.5)
     * @param Float quality2f 輸出圖片的透明度(質量,如0.8f默認0.5)
     * @param targetPath 輸出圖片的位置
     * @throws IOException
     */
    public static String waterMark(File file,File mark,String positon,Float quality1f,Float quality2f,String targetPath) throws IOException {
        
        try {
            String filename = file.getName();
            String endTag = filename.substring(filename.lastIndexOf(".")+1);
            String path = targetPath+"/"+filename+"_watermark";
            Float srcQual = null;
            Float targetQual = null;
            if(quality1f==null){
                srcQual = 0.5f;
            }else{
                srcQual = quality1f;
            }
            if(quality2f==null){
                targetQual = 0.8f;
            }else{
                targetQual = quality2f;
            }
            if(positon==null){
                path = path+"_center."+endTag;
                Thumbnails.of(file).watermark(
                        Positions.CENTER,
                        ImageIO.read(mark), srcQual)
                        .outputQuality(targetQual).toFile(path);
                return path;
            }else{
                if("CENTER".equalsIgnoreCase(positon)){
                    path = path+"_"+positon.toLowerCase()+"."+endTag;
                    Thumbnails.of(file).watermark(
                            Positions.CENTER,
                            ImageIO.read(mark), srcQual)
                            .outputQuality(targetQual).toFile(path);
                    return path;
                }else if("CENTER_LEFT".equalsIgnoreCase(positon)){
                    path = path+"_"+positon.toLowerCase()+"."+endTag;
                    Thumbnails.of(file).watermark(
                            Positions.CENTER_LEFT,
                            ImageIO.read(mark), srcQual)
                            .outputQuality(targetQual).toFile(path);
                    return path;
                }else if("CENTER_RIGHT".equalsIgnoreCase(positon)){
                    path = path+"_"+positon.toLowerCase()+"."+endTag;
                    Thumbnails.of(file).watermark(
                            Positions.CENTER_RIGHT,
                            ImageIO.read(mark), srcQual)
                            .outputQuality(targetQual).toFile(path);
                    return path;
                }else if("TOP_CENTER".equalsIgnoreCase(positon)){
                    path = path+"_"+positon.toLowerCase()+"."+endTag;
                    Thumbnails.of(file).watermark(
                            Positions.TOP_CENTER,
                            ImageIO.read(mark), srcQual)
                            .outputQuality(targetQual).toFile(path);
                    return path;
                }else if("TOP_LEFT".equalsIgnoreCase(positon)){
                    path = path+"_"+positon.toLowerCase()+"."+endTag;
                    Thumbnails.of(file).watermark(
                            Positions.TOP_LEFT,
                            ImageIO.read(mark), srcQual)
                            .outputQuality(targetQual).toFile(path);
                    return path;
                }else if("TOP_RIGHT".equalsIgnoreCase(positon)){
                    path = path+"_"+positon.toLowerCase()+"."+endTag;
                    Thumbnails.of(file).watermark(
                            Positions.TOP_RIGHT,
                            ImageIO.read(mark), srcQual)
                            .outputQuality(targetQual).toFile(path);
                    return path;
                }else if("BOTTOM_CENTER".equalsIgnoreCase(positon)){
                    path = path+"_"+positon.toLowerCase()+"."+endTag;
                    Thumbnails.of(file).watermark(
                            Positions.BOTTOM_CENTER,
                            ImageIO.read(mark), srcQual)
                            .outputQuality(targetQual).toFile(path);
                    return path;
                }else if("BOTTOM_LEFT".equalsIgnoreCase(positon)){
                    path = path+"_"+positon.toLowerCase()+"."+endTag;
                    Thumbnails.of(file).watermark(
                            Positions.BOTTOM_LEFT,
                            ImageIO.read(mark), srcQual)
                            .outputQuality(targetQual).toFile(path);
                    return path;
                }else if("BOTTOM_RIGHT".equalsIgnoreCase(positon)){
                    path = path+"_"+positon.toLowerCase()+"."+endTag;
                    Thumbnails.of(file).watermark(
                            Positions.BOTTOM_RIGHT,
                            ImageIO.read(mark), srcQual)
                            .outputQuality(targetQual).toFile(path);
                    return path;
                }else{
                    return "位置參數不正確";
                }
                
                
            }
            
            
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 裁剪
     * @param File
     * @param 要設置的位置  默認"CENTER"(可傳:"CENTER","CENTER_LEFT","CENTER_RIGHT",
     * "TOP_CENTER","TOP_LEFT","TOP_RIGHT","BOTTOM_CENTER","BOTTOM_LEFT","BOTTOM_RIGHT")
     * @param int width
     * @param targetPath 輸出圖片的位置
     * @throws IOException
     */
    public static void region(File file,String position,int width,int height,String targetPath) throws IOException {
        /**
         * 圖片中心400*400的區域
         */
        Thumbnails.of(file).sourceRegion(Positions.CENTER, width,
                height).size(width, height).keepAspectRatio(false).toFile(targetPath);
//        /**
//         * 圖片右下400*400的區域
//         */
//        Thumbnails.of("images/test.jpg").sourceRegion(Positions.BOTTOM_RIGHT,
//                400, 400).size(200, 200).keepAspectRatio(false).toFile(
//                "C:/image_region_bootom_right.jpg");
//        /**
//         * 指定座標
//         */
//        Thumbnails.of("images/test.jpg").sourceRegion(600, 500, 400, 400).size(
//                200, 200).keepAspectRatio(false).toFile(
//                "C:/image_region_coord.jpg");
    }
    
    /**
     * 裁剪
     * @param File
     * @param 要設置的位置  默認"CENTER"(可傳:"CENTER","CENTER_LEFT","CENTER_RIGHT",
     * "TOP_CENTER","TOP_LEFT","TOP_RIGHT","BOTTOM_CENTER","BOTTOM_LEFT","BOTTOM_RIGHT")
     * @param int width
     * @param targetPath 輸出圖片的位置
     * @throws IOException
     */
    public static BufferedImage region(InputStream inputStream,String fileName,int width,int height) throws IOException {
        
        if(fileName.indexOf("CENTER_LEFT")!=-1){
            return Thumbnails.of(inputStream).sourceRegion(Positions.CENTER_LEFT, width,
                    height).size(width, height).keepAspectRatio(false).asBufferedImage();
        }else if(fileName.indexOf("CENTER_RIGHT")!=-1){
            return Thumbnails.of(inputStream).sourceRegion(Positions.CENTER_RIGHT, width,
                    height).size(width, height).keepAspectRatio(false).asBufferedImage();
        }else if(fileName.indexOf("TOP_CENTER")!=-1){
            return Thumbnails.of(inputStream).sourceRegion(Positions.TOP_CENTER, width,
                    height).size(width, height).keepAspectRatio(false).asBufferedImage();
        }else if(fileName.indexOf("TOP_LEFT")!=-1){
            return Thumbnails.of(inputStream).sourceRegion(Positions.TOP_LEFT, width,
                    height).size(width, height).keepAspectRatio(false).asBufferedImage();
        }else if(fileName.indexOf("TOP_RIGHT")!=-1){
            return Thumbnails.of(inputStream).sourceRegion(Positions.TOP_RIGHT, width,
                    height).size(width, height).keepAspectRatio(false).asBufferedImage();
        }else if(fileName.indexOf("BOTTOM_CENTER")!=-1){
            return Thumbnails.of(inputStream).sourceRegion(Positions.BOTTOM_CENTER, width,
                    height).size(width, height).keepAspectRatio(false).asBufferedImage();
        }else if(fileName.indexOf("BOTTOM_LEFT")!=-1){
            return Thumbnails.of(inputStream).sourceRegion(Positions.BOTTOM_LEFT, width,
                    height).size(width, height).keepAspectRatio(false).asBufferedImage();
        }else if(fileName.indexOf("BOTTOM_RIGHT")!=-1){
            return Thumbnails.of(inputStream).sourceRegion(Positions.BOTTOM_RIGHT, width,
                    height).size(width, height).keepAspectRatio(false).asBufferedImage();
        }else{
            return Thumbnails.of(inputStream).sourceRegion(Positions.CENTER, width,
                    height).size(width, height).keepAspectRatio(false).asBufferedImage();
        }
    }
    
    public static void region(BufferedImage bufferImage,OutputStream os,String fileName) throws IOException {
        
        Integer width = null;
        Integer height = null;
        int w = bufferImage.getWidth();
        int h = bufferImage.getHeight();
        
        if(fileName.indexOf("_")!=-1){
            String name = fileName.substring(0,fileName.lastIndexOf("."));//去除後綴
            String endTag = fileName.substring(fileName.lastIndexOf(".")+1);
            String size = name.substring(name.lastIndexOf("_")+1);
            String[] sizes = size.split("x");
            Pattern pattern = Pattern.compile("[0-9]*");
            boolean isNum = pattern.matcher(sizes[0]).matches();
            if(isNum){
                width = Integer.parseInt(sizes[0]);
                height = Integer.parseInt(sizes[1]);
                w = bufferImage.getWidth();
                h = bufferImage.getHeight();
                if(width.intValue()>w){
                    width = w;
                }
                if(height.intValue()>h){
                    height = h;
                }
            }else{
                
                width = 80;   //默認壓成80寬
                height = 80;  //默認壓成80高
                if(80>w){
                    width = w;
                }
                if(80>h){
                    height = h;
                }
            }
            
            if(fileName.indexOf("CENTER_LEFT")!=-1){
                Thumbnails.of(bufferImage).sourceRegion(Positions.CENTER_LEFT, width,height)
                .size(width, height).outputFormat(endTag).toOutputStream(os);
//                Thumbnails.of(bufferImage).sourceRegion(Positions.CENTER_LEFT, width,height)
//                .size(width, height).keepAspectRatio(false).toFile(new File("c:\\test2.jpg"));
            }else if(fileName.indexOf("CENTER_RIGHT")!=-1){
                Thumbnails.of(bufferImage).sourceRegion(Positions.CENTER_RIGHT, width,height)
                .size(width, height).keepAspectRatio(false).outputFormat(endTag).toOutputStream(os);
            }else if(fileName.indexOf("TOP_CENTER")!=-1){
                Thumbnails.of(bufferImage).sourceRegion(Positions.TOP_CENTER, width,height)
                .size(width, height).keepAspectRatio(false).outputFormat(endTag).toOutputStream(os);
            }else if(fileName.indexOf("TOP_LEFT")!=-1){
                Thumbnails.of(bufferImage).sourceRegion(Positions.TOP_LEFT, width,height)
                .size(width, height).keepAspectRatio(false).outputFormat(endTag).toOutputStream(os);
            }else if(fileName.indexOf("TOP_RIGHT")!=-1){
                Thumbnails.of(bufferImage).sourceRegion(Positions.TOP_RIGHT, width,height)
                .size(width, height).keepAspectRatio(false).outputFormat(endTag).toOutputStream(os);
            }else if(fileName.indexOf("BOTTOM_CENTER")!=-1){
                Thumbnails.of(bufferImage).sourceRegion(Positions.BOTTOM_CENTER, width,height)
                .size(width, height).keepAspectRatio(false).outputFormat(endTag).toOutputStream(os);
            }else if(fileName.indexOf("BOTTOM_LEFT")!=-1){
                Thumbnails.of(bufferImage).sourceRegion(Positions.BOTTOM_LEFT, width,height)
                .size(width, height).keepAspectRatio(false).outputFormat(endTag).toOutputStream(os);
            }else if(fileName.indexOf("BOTTOM_RIGHT")!=-1){
                Thumbnails.of(bufferImage).sourceRegion(Positions.BOTTOM_RIGHT, width,height)
                .size(width, height).keepAspectRatio(false).outputFormat(endTag).toOutputStream(os);
            }else{
                Thumbnails.of(bufferImage).sourceRegion(Positions.CENTER, width,height)
                .size(width, height).keepAspectRatio(false).outputFormat(endTag).toOutputStream(os);
            }
            
            //return Thumbnails.of(file).sourceRegion(Positions.CENTER, width,height).size(width, height).keepAspectRatio(false).asBufferedImage();
        }
        
    }

    /**
     * 轉化圖像格式
     * @param File
     * @param String format 傳圖片格式,如‘png’
     * @throws IOException
     */
    public static String outputFormat(File file,String format,String targetPath) throws IOException {

        String filename = file.getName();
        String path = targetPath + "/" + filename + "_" + format + "." + format;

        Thumbnails.of(file).outputFormat(format.toLowerCase()).toFile(path);
        return path;
//        Thumbnails.of("images/test.jpg").size(1280, 1024).outputFormat("png")
//                .toFile("C:/image_1280x1024.png");
//        Thumbnails.of("images/test.jpg").size(1280, 1024).outputFormat("gif")
//                .toFile("C:/image_1280x1024.gif");
    }

    /**
     * 輸出到OutputStream
     *
     * @throws IOException
     */
    public static String toOutputStream(File file,String targetPath) throws IOException {
        /**
         * toOutputStream(流對象)
         * OutputStream os = new FileOutputStream(
                "C:/image_1280x1024_OutputStream.png");
        Thumbnails.of("images/test.jpg").size(1280, 1024).toOutputStream(os);
         *
         */
        try {
            OutputStream os = new FileOutputStream(file);
            Thumbnails.of(targetPath).toOutputStream(os);
            return "";
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
        
        
    }

    /**
     * 輸出到BufferedImage
     *
     * @throws IOException
     */
    public static String bufferedImage(File file,String targetPath,String format) throws IOException {
        /**
         * asBufferedImage() 返回BufferedImage
         */
        String filename = file.getName();
        String endTag = filename.substring(filename.lastIndexOf(".")+1);
        String path = targetPath+"/"+filename+"_BufferedImage"+"."+endTag;
        BufferedImage thumbnail = Thumbnails.of(file).asBufferedImage();
        ImageIO.write(thumbnail, format, new File(path));
        return path;
    }
    
    public static void main(String[] args) throws IOException {
        File file = new File("C:\\1234567heng_80x80.jpg");
        //region(file,"center",300,100,"c:\\123456t.jpg");
        
        //scaleBySize(file,600,100,"c:\\");
        InputStream inputStream = new FileInputStream(file);
        OutputStream out = new FileOutputStream(new File("c:\\test3.jpg"));
        
        //BufferedImage img = scaleBySize(inputStream,file.getName());
        //ImageIO.write(img,"jpg", new File("C:/test1.jpg"));
        //region(img,out,"1234567heng_80x80.jpg");
//        Thumbnails.of(img).sourceRegion(Positions.CENTER_LEFT, 100,50)
//        .size(100, 50).outputFormat("jpg").toOutputStream(out);
        
    }
    
}


java

相關文章
相關標籤/搜索