圖片壓縮以及位深度轉換

需求:作一個電子簽章圖片上傳,而後在線截取並上傳到後臺,再對圖片進行格式化處理,包括位深度8位,gif格式,刪除元數據javascript

 

實現:html

1,先在前臺使用了一個cropbox.js的插件,這個插件能實現圖片上傳並在線預覽剪切等功能,並將截取後的圖片以base64的格式傳向後臺java

var options = {
        thumbBox: '.thumbBox',
        spinner: '.spinner',
        imgSrc: ''
    }
    var cropper = $('.imageBox').cropbox(options);
    $('#upload-file').on('change', function () {
        var reader = new FileReader();
        reader.onload = function (e) {
            options.imgSrc = e.target.result;
            cropper = $('.imageBox').cropbox(options);
            $('#spinner').html('');
        }
        reader.readAsDataURL(this.files[0]);
    })
    $('#btnCrop').on('click', function () {
        //判斷是否發生改變
        var bigContent = $('#spinner').html();
        if(bigContent.indexOf("圖片") > 0){
            $window.alert("圖片沒上傳,請不要點擊裁切")
            return false;
        }
        var img = cropper.getDataURL();
        $('#croppedAdd').html('');
        $('#croppedAdd').append('<img src="' + img + '" style="height: 200px;width: 200px;border: 1px solid #000000;" id="truePic" align="absmiddle" >');
    })

2,在後臺接收base64, 去掉格式頭,而後先生成一個png格式的圖片app

base64 = base64.split(",")[1];
		BASE64Decoder decoder = new BASE64Decoder();
		String FilePath = "";
		try{
			//Base64解碼
			byte[] b = decoder.decodeBuffer(base64);
			for(int i=0;i<b.length;++i)	{
				if(b[i]<0) {//調整異常數據
					b[i]+=256;
				}
			}
			//生成png圖片
			String fileName = UUID.randomUUID().toString().replace("-", "")+".png";

			//本地絕對路徑
			String imgFilePath = path + fileName;
			OutputStream out = new FileOutputStream(imgFilePath);

            //生成完畢,開始調用壓縮方法,刪除原圖片,保留最後生成的圖片
			FilePath = PicUtils.commpressPicForScale(imgFilePath, path + destFileName, 20, 0.9);

			out.write(b);
			out.flush();
			out.close();

3,先轉換8位,再判斷內存大小並進行圖片壓縮dom

//在生成圖片之後調用,以0.9的比例進行壓縮
//FilePath = PicUtils.commpressPicForScale(imgFilePath, path + destFileName, 20, 0.9);

    public static String commpressPicForScale(String srcPath, String desPath,long desFileSize, double accuracy) {
        if (PubFun.isEmpty(srcPath) || PubFun.isEmpty(srcPath)) {
            return null;
        }
        if (!new File(srcPath).exists()) {
            return null;
        }
        try {
            //轉換路徑,將base64生成的png圖片轉換成gif圖片
            convertToEight(srcPath, desPath);

            File srcFileJPG = new File(desPath);
            long srcFileSizeJPG = srcFileJPG.length();
            //判斷大小,若是小於20kb,不壓縮;若是大於等於20kb,壓縮
            if (srcFileSizeJPG <= desFileSize * 1024) {
                return desPath;
            }
            commpressPicCycle(desPath, desFileSize, accuracy);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return desPath;
    }
    private static void commpressPicCycle(String desPath, long desFileSize,double accuracy) throws IOException {
        File srcFileJPG = new File(desPath);
        long srcFileSizeJPG = srcFileJPG.length();
        if (srcFileSizeJPG <= desFileSize * 1024) {
            return;
        }
        Thumbnails.of(desPath).scale(1f).outputQuality(accuracy).toFile(desPath);
        commpressPicCycle(desPath, desFileSize, accuracy);
    }
    /**
     * 轉換8位(從32位png格式圖片轉換成8位gif格式圖片)
     */
    private static void convertToEight(String pngPath, String destination) throws IOException {
        //讀取png圖片路徑
        ImageIcon ii = new ImageIcon(new File(pngPath).getCanonicalPath());
        Image i = ii.getImage();
        Image resizedImage = i.getScaledInstance(198, 198, Image.SCALE_SMOOTH);
        Image temp = new ImageIcon(resizedImage).getImage();
        BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null), BufferedImage.TYPE_INT_BGR);

        Graphics2D gd = bufferedImage.createGraphics();
        bufferedImage = gd.getDeviceConfiguration().createCompatibleImage(198, 198, Transparency.TRANSLUCENT);
        gd = bufferedImage.createGraphics();
        gd.drawImage(temp, 0, 0, null);

        ImageIO.write(bufferedImage, "gif", new File(destination));
    }

中間的代碼借鑑了不少前輩的關於圖片處理的代碼,轉8位最主要的是read的方式,TYPE_INT_BGR就能夠讀出8位的,說的不對的還請指正this

相關文章
相關標籤/搜索