java input 實現調用手機相機和本地照片上傳圖片到服務器然後壓縮

在微信公衆號裏面需要上傳頭像,時間比較緊,調用學習jssdk並使用 來不及  就用了input

  1. 使用input:file標籤, 去調用系統默認相機,攝像,錄音功能,其實是有個capture屬性,直接說明需要調用什麼功能

    <input type="file" accept="image/*" capture="camera">

    <input type="file" accept="video/*" capture="camcorder">

    <input type="file" accept="audio/*" capture="microphone">

    capture表示,可以捕獲到系統默認的設備,比如:camera--照相機;camcorder--攝像機;microphone--錄音。

    accept表示,直接打開系統文件目錄。

  2. input:file標籤還支持一個multiple屬性,表示可以支持多選,如:

    <input type="file" accept="image/*" multiple>

    加上這個multiple後,capture就沒啥用了,因爲multiple是專門用來支持多選的。

用form表單提交

 <form id="uploadForm" class="mui-input-group" style="width: 80%;margin: 0 auto;margin-top: 70px" action="/jxs/uploadtou.do" method="post" enctype="multipart/form-data" >
        <div class="mui-input-row">
            <label>圖片</label>
            <input required="required" class="mui-input-clear mui-input" type="file" name="file" id="photo_pick"  accept="image/*">
        </div>

        <div class="mui-content-padded" style="width: 90%;margin: 0 auto;margin-top: 5px;padding: 10px">
            <input style="color:#FFFFFF  ;width: 100%;background: #00F7DE" value="上傳" type="submit">
        </div>
    </form>

上傳之後圖片顯示在頁面上

<div class="progress_dialog" style="margin-left:30px;margin-top:20px;width: 50%;height: 50%;"></div>

js

<script>
    /*圖片地址
    https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E9%AB%98%E6%B8%85%E7%BE%8E%E5%A5%B3%20%E4%B8%9D%E8%A2%9C%E5%B7%A8%E4%B9%B3&step_word=&hs=0&pn=1&spn=0&di=57234189540&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=2&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=-1&cs=3589338782%2C536437810&os=3988412231%2C488396405&simid=3515890414%2C233897128&adpicid=0&lpn=0&ln=1389&fr=&fmq=1490709487003_R&fm=result&ic=0&s=undefined&se=&sme=&tab=0&width=&height=&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=&objurl=http%3A%2F%2Fwww.bz55.com%2Fuploads%2Fallimg%2F150416%2F139-1504161AK9.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3Bkzcc_z%26e3Bv54AzdH3F4jtgektzitAzdH3F8l9c9_z%26e3Bip4s&gsm=0&rpstart=0&rpnum=0
    */
    $(function() {
        $("#photo_pick").on("change", function () {
            var file = this.files[0];
            photoCompress(file, 50, $(".progress_dialog")[0])
            $(".progress_dialog").show();
            if (!this.files.length) return;
            var files = Array.prototype.slice.call(this.files);
            if (files.length > 9) {
                alert("最多同時只可上傳9張圖片");
                return;
            }
        /*    files.forEach(function (file, i) {
                /!*var reader = new FileReader();
                reader.onload = function () {
                    var imgO = document.createElement("img");
                    imgO.src = reader.result;
                }*!/
                reader.readAsDataURL(file);
                $(".progress_dialog").hide();*/
            });
        })


        /*
    三個參數
    file:一個是文件(類型是圖片格式),
    w:一個是文件壓縮的後寬度,寬度越小,字節越小
    objDiv:一個是容器或者回調函數
    photoCompress()
     */
        function photoCompress(file, w, objDiv) {
            var ready = new FileReader();
            /*開始讀取指定的Blob對象或File對象中的內容. 當讀取操作完成時,readyState屬性的值會成爲DONE,如果設置了onloadend事件處理程序,則調用之.同時,result屬性中將包含一個data: URL格式的字符串以表示所讀取文件的內容.*/
            ready.readAsDataURL(file);
            ready.onload = function () {
                var re = this.result;
                canvasDataURL(re, w, objDiv)

            }
        }

        function canvasDataURL(re, w, objDiv) {
            var newImg = new Image();
            newImg.src = re;
            var imgWidth, imgHeight, offsetX = 0, offsetY = 0;
            newImg.onload = function () {
                var img = document.createElement("img");
                img.src = newImg.src;
                imgWidth = img.width;
                imgHeight = img.height;
                var canvas = document.createElement("canvas");
                canvas.width = w;
                canvas.height = w;
                var ctx = canvas.getContext("2d");
                ctx.clearRect(0, 0, w, w);
                if (imgWidth > imgHeight) {
                    imgWidth = w * imgWidth / imgHeight;
                    imgHeight = w;
                    offsetX = -Math.round((imgWidth - w) / 6);
                } else {
                    imgHeight = w * imgHeight / imgWidth;
                    imgWidth = w;
                    offsetY = -Math.round((imgHeight - w) / 6);
                }
                ctx.drawImage(img, offsetX, offsetY, imgWidth, imgHeight);
                var base64 = canvas.toDataURL("image/jpeg", 0.1);
                if (typeof objDiv == "object") {
                    objDiv.appendChild(canvas);
                } else if (typeof objDiv == "function") {
                    objDiv(base64);
                }
            }

    }
</script>

 

後臺接收以及壓縮

     System.out.println(file);
        String result = "";
        if (!file.isEmpty()) {
            try {
                Shopuser u = (Shopuser) request.getSession().getAttribute("currentUser");
                String extName = file.getOriginalFilename();
                String fileName = file.getName();
                String suffix = extName.substring(extName.lastIndexOf(".") + 1);
                System.err.println(suffix);
                Date now = new Date();
                SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                String s = outFormat.format(now);
                BufferedOutputStream bos = new BufferedOutputStream(
                        new FileOutputStream(new File("D:\\xiangmu\\demo\\" + s + "." + suffix)));
                bos.write(file.getBytes());
                bos.flush();
                bos.close();
                /**
                 * compress 圖片縮放類的使用(縮略圖)
                 * srcImage 爲InputStream對象
                 * Rectangle    爲需要截圖的長方形座標
                 * proportion 爲壓縮比例
                 * **/
                InputStream in = null;
                //縮放後需要保存的路徑
                File saveFile = new File("D:\\xiangmu\\demo\\" + s + s + "." + suffix);
                try {
                    //原圖片的路徑
                    in = new FileInputStream(new File("D:\\xiangmu\\demo\\" + s + "." + suffix));
                    int length = in.available();
                    if (length / 1024 >= 10 && length / 1024 < 100) {
                        if (compress(in, saveFile, 10)) {
                            System.out.println("圖片壓縮十倍!");
                        }
                    } else if (length / 1024 >= 100 && length / 1024 < 1000) {
                        if (compress(in, saveFile, 100)) {
                            System.out.println("圖片壓縮100倍!");
                        }
                    } else if (length / 1024 >= 1000 && length / 1024 < 10000) {
                        if (compress(in, saveFile, 1000)) {
                            System.out.println("圖片壓縮1000倍!");
                        }
                    } else if (length / 1024 < 10 && length / 1024 > 0) {
                        if (compress(in, saveFile, 1)) {
                            System.out.println("圖片壓縮1倍!");
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    in.close();
                }
                String filename = "/Path/" + s + s + "." + suffix;//服務器地址
                System.out.println(filename);
                int a = shopService.updateImg(u.getId(), filename);
                System.out.println(filename);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
        }

        return "wode.html";
    }

 

 

圖片處理類

 

package com.example.springbootshop.util;

import org.junit.Test;

import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;





/**
 * 圖片工具類,完成圖片的截取
 * 所有方法返回值均未boolean型
 */
public class ImageHelper {
    /**
     * 實現圖像的等比縮放
     * @param source
     * @param targetW
     * @param targetH
     * @return
     */
    private static BufferedImage resize(BufferedImage source, int targetW,
                                        int targetH) {
        // targetW,targetH分別表示目標長和寬
        int type = source.getType();
        BufferedImage target = null;
        double sx = (double) targetW / source.getWidth();
        double sy = (double) targetH / source.getHeight();
        // 這裏想實現在targetW,targetH範圍內實現等比縮放。如果不需要等比縮放
        // 則將下面的if else語句註釋即可
        if (sx < sy) {
            sx = sy;
            targetW = (int) (sx * source.getWidth());
        } else {
            sy = sx;
            targetH = (int) (sy * source.getHeight());
        }
        if (type == BufferedImage.TYPE_CUSTOM) { // handmade
            ColorModel cm = source.getColorModel();
            WritableRaster raster = cm.createCompatibleWritableRaster(targetW,
                    targetH);
            boolean alphaPremultiplied = cm.isAlphaPremultiplied();
            target = new BufferedImage(cm, raster, alphaPremultiplied, null);
        } else
            target = new BufferedImage(targetW, targetH, type);
        Graphics2D g = target.createGraphics();
        // smoother than exlax:
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
        g.dispose();
        return target;
    }

    /**
     * 實現圖像的等比縮放和縮放後的截取, 處理成功返回true, 否則返回false
     * @param inFilePath 要截取文件的路徑
     * @param outFilePath 截取後輸出的路徑
     * @param width 要截取寬度
     * @param hight 要截取的高度
     * @throws Exception
     */
    public static boolean compress(String inFilePath, String outFilePath,
                                   int width, int hight) {
        boolean ret = false;
        File file = new File(inFilePath);
        File saveFile = new File(outFilePath);
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            ret = compress(in, saveFile, width, hight);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            ret = false;
        } finally{
            if(null != in){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return ret;
    }

    /**
     * 實現圖像的等比縮放和縮放後的截取, 處理成功返回true, 否則返回false
     * @param in 要截取文件流
     * @param outFilePath 截取後輸出的路徑
     * @param width 要截取寬度
     * @param hight 要截取的高度
     * @throws Exception
     */
    public static boolean compress(InputStream in, File saveFile,
                                   int width, int hight) {
//     boolean ret = false;
        BufferedImage srcImage = null;
        try {
            srcImage = ImageIO.read(in);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        if (width > 0 || hight > 0) {
            // 原圖的大小
            int sw = srcImage.getWidth();
            int sh = srcImage.getHeight();
            // 如果原圖像的大小小於要縮放的圖像大小,直接將要縮放的圖像複製過去
            if (sw > width && sh > hight) {
                srcImage = resize(srcImage, width, hight);
            } else {
                String fileName = saveFile.getName();
                String formatName = fileName.substring(fileName
                        .lastIndexOf('.') + 1);
                try {
                    ImageIO.write(srcImage, formatName, saveFile);
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
                return true;
            }
        }
        // 縮放後的圖像的寬和高
        int w = srcImage.getWidth();
        int h = srcImage.getHeight();
        // 如果縮放後的圖像和要求的圖像寬度一樣,就對縮放的圖像的高度進行截取
        if (w == width) {
            // 計算X軸座標
            int x = 0;
            int y = h / 2 - hight / 2;
            try {
                saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile);
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        // 否則如果是縮放後的圖像的高度和要求的圖像高度一樣,就對縮放後的圖像的寬度進行截取
        else if (h == hight) {
            // 計算X軸座標
            int x = w / 2 - width / 2;
            int y = 0;
            try {
                saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile);
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }

        return true;
    }

    /**
     * 實現圖像的等比縮放和縮放後的截取, 處理成功返回true, 否則返回false
     * @param in 圖片輸入流
     * @param saveFile 壓縮後的圖片輸出流
     * @param proportion 壓縮比
     * @throws Exception
     */
    public static boolean compress(InputStream in, File saveFile, int proportion) {
        if(null == in
                ||null == saveFile
                ||proportion < 1){// 檢查參數有效性
            //LoggerUtil.error(ImageHelper.class, "--invalid parameter, do nothing!");
            return false;
        }

        BufferedImage srcImage = null;
        try {
            srcImage = ImageIO.read(in);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        // 原圖的大小
        int width = srcImage.getWidth() / proportion;
        int hight = srcImage.getHeight() / proportion;

        srcImage = resize(srcImage, width, hight);

        // 縮放後的圖像的寬和高
        int w = srcImage.getWidth();
        int h = srcImage.getHeight();
        // 如果縮放後的圖像和要求的圖像寬度一樣,就對縮放的圖像的高度進行截取
        if (w == width) {
            // 計算X軸座標
            int x = 0;
            int y = h / 2 - hight / 2;
            try {
                saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile);
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        // 否則如果是縮放後的圖像的高度和要求的圖像高度一樣,就對縮放後的圖像的寬度進行截取
        else if (h == hight) {
            // 計算X軸座標
            int x = w / 2 - width / 2;
            int y = 0;
            try {
                saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile);
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }

        return true;
    }

    /**
     * 實現縮放後的截圖
     * @param image 縮放後的圖像
     * @param subImageBounds 要截取的子圖的範圍
     * @param subImageFile 要保存的文件
     * @throws IOException
     */
    private static void saveSubImage(BufferedImage image,
                                     Rectangle subImageBounds, File subImageFile) throws IOException {
        if (subImageBounds.x < 0 || subImageBounds.y < 0
                || subImageBounds.width - subImageBounds.x > image.getWidth()
                || subImageBounds.height - subImageBounds.y > image.getHeight()) {
            //LoggerUtil.error(ImageHelper.class, "Bad subimage bounds");
            return;
        }
        BufferedImage subImage = image.getSubimage(subImageBounds.x,subImageBounds.y, subImageBounds.width, subImageBounds.height);
        String fileName = subImageFile.getName();
        String formatName = fileName.substring(fileName.lastIndexOf('.') + 1);
        ImageIO.write(subImage, formatName, subImageFile);
    }


    @Test
    public static void main(String[] args) throws Exception {

        /**
         * saveSubImage 截圖類的使用
         * srcImage 爲BufferedImage對象
         * Rectangle    爲需要截圖的長方形座標
         * saveFile 需要保存的路徑及名稱
         * **/
        //需要截圖的長方形座標
        /*Rectangle rect =new Rectangle();
        rect.x=40;
        rect.y=40;
        rect.height=160;
        rect.width=160;

        InputStream in = null;
        //需要保存的路徑及名稱
        File saveFile = new File("d:\\ioc\\files\\aaa2.jpg");
        //需要進行處理的圖片的路徑
        in = new FileInputStream(new File("d:\\ioc\\files\\aaa.jpg"));
        BufferedImage srcImage = null;
        //將輸入的數據轉爲BufferedImage對象
        srcImage = ImageIO.read(in);

        ImageHelper img=new ImageHelper();
        img.saveSubImage(srcImage, rect, saveFile);*/

        /**
         * compress 圖片縮放類的使用(縮略圖)
         * srcImage 爲InputStream對象
         * Rectangle    爲需要截圖的長方形座標
         * proportion 爲壓縮比例
         * **/
        InputStream in = null;
        //縮放後需要保存的路徑
        File saveFile = new File("D:\\xiangmu\\demo\\20180523192742IMG_0049123.jpg");
        try {
            //原圖片的路徑
            in = new FileInputStream(new File("D:\\xiangmu\\demo\\20180523192742IMG_0049.jpg"));
            if(compress(in, saveFile, 10)){
                System.out.println("圖片壓縮十倍!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            in.close();
        }
    }
}
發佈了125 篇原創文章 · 獲贊 67 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章