java縮放圖片、java裁剪圖片代碼工具類

來源:互聯網
上載者:User

java縮放圖片、java裁剪圖片代碼工具類

在系統的上傳圖片功能中,我們無法控制使用者上傳圖片的大小,使用者可能會上傳大到幾十M小到1k的的圖片,一方面圖片太大佔據了太多的空間,另一方面,我們沒辦法在頁面上顯示統一大小的圖片。所以我們需要對使用者上傳的圖片進行縮放和裁剪,這裡的縮放和平常的壓縮不是一個意思,因為要實現小的圖片會放大,大的圖片會縮小,而且是等比例變的,圖片不會顯示擠壓的效果。而這種操作java完全可以實現。下面分享下java縮放、裁剪圖片的工具類。

一、首先看下效果:

1.jpg為原圖,yasuo.jpg是縮放後的,caijian.jpg是在yasuo.jpg基礎上裁掉兩邊各10像素得到的

vc8xLmpwZ6Osyseyu8rHvMjNvMas0KHBy6Os09a1w7W9wcvP69KqtcTNvMastPPQoaOstvjH0s28xqzDu9PQsbu8t9G5PyDPwsPmwLS/tLT6wuujujwvcD4NCjxoMiBpZD0="二工具類">二、工具類:

import java.awt.Color;import java.awt.Graphics2D;import java.awt.Image;import java.awt.geom.AffineTransform;import java.awt.image.AffineTransformOp;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;/** * 裁剪、縮放圖片工具類 * @author CSDN 沒有夢想-何必遠方  */public class ImgUtils {    /**     * 縮放圖片方法     * @param srcImageFile 要縮放的圖片路徑     * @param result 縮放後的圖片路徑     * @param height 目標高度像素     * @param width  目標寬度像素       * @param bb     是否補白     */     public final static void scale(String srcImageFile, String result, int height, int width, boolean bb) {            try {                double ratio = 0.0; // 縮放比例               File f = new File(srcImageFile);                BufferedImage bi = ImageIO.read(f);                Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);//bi.SCALE_SMOOTH  選擇映像平滑度比縮放速度具有更高優先順序的映像縮放演算法。                // 計算比例               if ((bi.getHeight() > height) || (bi.getWidth() > width)) {                   double   ratioHeight = (new Integer(height)).doubleValue()/ bi.getHeight();                   double   ratioWhidth = (new Integer(width)).doubleValue()/ bi.getWidth();                   if(ratioHeight>ratioWhidth){                       ratio= ratioHeight;                   }else{                       ratio= ratioWhidth;                   }                    AffineTransformOp op = new AffineTransformOp(AffineTransform//仿射轉換                            .getScaleInstance(ratio, ratio), null);//返回表示剪下變換的變換                    itemp = op.filter(bi, null);//轉換源 BufferedImage 並將結果儲存在目標 BufferedImage 中。                }                if (bb) {//補白                   BufferedImage image = new BufferedImage(width, height,                            BufferedImage.TYPE_INT_RGB);//構造一個類型為預定義映像類型之一的 BufferedImage。                    Graphics2D g = image.createGraphics();//建立一個 Graphics2D,可以將它繪製到此 BufferedImage 中。                    g.setColor(Color.white);//控制顏色                    g.fillRect(0, 0, width, height);// 使用 Graphics2D 內容相關的設定,填充 Shape 的內部地區。                    if (width == itemp.getWidth(null))                        g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,                                itemp.getWidth(null), itemp.getHeight(null),                                Color.white, null);                    else                        g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,                                itemp.getWidth(null), itemp.getHeight(null),                                Color.white, null);                    g.dispose();                    itemp = image;                }                ImageIO.write((BufferedImage) itemp, "JPEG", new File(result));      //輸出壓縮圖片            } catch (IOException e) {                e.printStackTrace();            }        }     /**      * 裁剪圖片方法      * @param bufferedImage 映像源      * @param startX 裁剪開始x座標      * @param startY 裁剪開始y座標      * @param endX 裁剪結束x座標      * @param endY 裁剪結束y座標      * @return      */     public static BufferedImage cropImage(BufferedImage bufferedImage, int startX, int startY, int endX, int endY) {            int width = bufferedImage.getWidth();            int height = bufferedImage.getHeight();            if (startX == -1) {                startX = 0;            }            if (startY == -1) {                startY = 0;            }            if (endX == -1) {                endX = width - 1;            }            if (endY == -1) {                endY = height - 1;            }            BufferedImage result = new BufferedImage(endX - startX, endY - startY, 4);            for (int x = startX; x < endX; ++x) {                for (int y = startY; y < endY; ++y) {                    int rgb = bufferedImage.getRGB(x, y);                    result.setRGB(x - startX, y - startY, rgb);                }            }            return result;        }}
三、測試類別:
import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;import com.etoak.util.ImgUtils;public class Test {    public static void main(String[] args) throws IOException {        String path="C:/1.jpg";    //輸入圖片  測試要在C盤放一張圖片1.jpg        ImgUtils.scale("C:/1.jpg","C:/yasuo.jpg", 180, 240, true);//等比例縮放  輸出縮放圖片        File newfile=new File("C:/yasuo.jpg");           BufferedImage bufferedimage=ImageIO.read(newfile);        int width = bufferedimage.getWidth();        int height = bufferedimage.getHeight();        //目標將圖片裁剪成 寬240,高160        if (width > 240) {                                                            /*開始x座標              開始y座標             結束x座標                     結束y座標*/            bufferedimage=ImgUtils.cropImage(bufferedimage,(int) ((width - 240) / 2),0,(int) (width - (width-240) / 2),(int) (height)                    );            if (height > 160) {                bufferedimage=ImgUtils.cropImage(bufferedimage,0,(int) ((height - 160) / 2),240,(int) (height - (height - 160) / 2)                        );            }        }else{            if (height > 160) {                bufferedimage=ImgUtils.cropImage(bufferedimage,0,(int) ((height - 160) / 2),(int) (width),(int) (height - (height - 160) / 2)                        );            }        }        ImageIO.write(bufferedimage, "jpg", new File("C:/caijian.jpg"));    //輸出裁剪圖片    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.