H5+jqweui實現手機端圖片壓縮上傳 Base64

H5+jqweui實現手機端圖片壓縮上傳

主要功能,使用H5的formData上傳base64格式的圖片,canvas壓縮圖片,前端樣式使用weui,為方便起見,使用了jquery封裝過的weui,jqweui。

話不多少,開始上代碼。

前端代碼,直接在jqweui官網下的demo里改的(是dist下的demo)

復制代碼
<!DOCTYPE html>
<html><head><title>jQuery WeUI</title><meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"><meta name="description" content="Write an awesome description for your new site here. You can edit this line in _config.yml. It will appear in your document head meta (for Google search results) and in your feed.xml site description.
"><link rel="stylesheet" href="../lib/weui.min.css">
<link rel="stylesheet" href="../css/jquery-weui.css">
<link rel="stylesheet" href="css/demos.css"></head><body ontouchstart><header class='demos-header'><h1 class="demos-title">Uploader</h1></header><div class="weui-cells weui-cells_form"><div class="weui-cell"><div class="weui-cell__bd"><div class="weui-uploader"><div class="weui-uploader__hd"><p class="weui-uploader__title">圖片上傳</p><div class="weui-uploader__info">0/2</div></div><div class="weui-uploader__bd"><ul class="weui-uploader__files" id="uploaderFiles"><li class="weui-uploader__file" style="background-image:url(./images/pic_160.png)"></li></ul><div class="weui-uploader__input-box"><input id="uploaderInput" class="weui-uploader__input" type="file" accept="image/*" multiple=""></div></div></div></div></div></div><script src="../lib/jquery-2.1.4.js"></script>
<script src="../lib/fastclick.js"></script>
<script>$(function() {FastClick.attach(document.body);});
</script>
<script src="../js/jquery-weui.js"></script>
<script>$(function () {  // 允許上傳的圖片類型  var allowTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'];  // 1024KB,也就是 1MB  var maxSize = 2048 * 2048;  // 圖片最大寬度  var maxWidth = 10000;  // 最大上傳圖片數量  var maxCount = 6;  $('#uploaderInput').on('change', function (event) {  var files = event.target.files;  //console.log(files);return false;// 如果沒有選中文件,直接返回  if (files.length === 0) {  return;  }  for (var i = 0, len = files.length; i < len; i++) {  var file = files[i];  var reader = new FileReader();  // 如果類型不在允許的類型范圍內  if (allowTypes.indexOf(file.type) === -1) {  $.alert("該類型不允許上傳!", "警告!");              continue;  }  if (file.size > maxSize) {  //$.weui.alert({text: '圖片太大,不允許上傳'});
                $.alert("圖片太大,不允許上傳", "警告!");              continue;  }  if ($('.weui-uploader__file').length >= maxCount) {  $.weui.alert({text: '最多只能上傳' + maxCount + '張圖片'});  return;  }  reader.readAsDataURL(file);  reader.onload = function (e) {//console.log(e);var img = new Image(); img.src = e.target.result;         img.onload = function () {  // 不要超出最大寬度  var w = Math.min(maxWidth, img.width);  // 高度按比例計算  var h = img.height * (w / img.width);  var canvas = document.createElement('canvas');  var ctx = canvas.getContext('2d');  // 設置 canvas 的寬度和高度  
                    canvas.width = w;  canvas.height = h;  ctx.drawImage(img, 0, 0, w, h); 
            
var base64 = canvas.toDataURL('image/jpeg',0.8); //console.log(base64);// 插入到預覽區 var $preview = $('<li class="weui-uploader__file weui-uploader__file_status" style="background-image:url(' + img.src + ')"><div class="weui-uploader__file-content">0%</div></li>'); $('#uploaderFiles').append($preview); var num = $('.weui-uploader__file').length; $('.weui-uploader__info').text(num + '/' + maxCount); var formData = new FormData();formData.append("images", base64);//console.log(img.src); $.ajax({url: "savetofile.php",type: 'POST',data: formData,contentType:false,processData:false,success: function(data){$preview.removeClass('weui-uploader__file_status');$.toast("上傳成功", function() {//console.log('close'); });},error: function(xhr, type){alert('Ajax error!')}});}; }; } }); }); </script></body> </html>
復制代碼

上述代碼中

 var base64 = canvas.toDataURL('image/jpeg',0.8); 

只有這個函數的第一個參數為image/jpeg是壓縮功能才可正常使用,第二個參數為壓縮比例

php代碼,對base64格式的圖片解碼并保存

復制代碼
<?php$imgData = $_REQUEST['images'];
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $imgData, $result)){$type = $result[2];$rand = rand(1000,9999);$new_file = 'img/'.$rand.'.'.$type;if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $imgData)))){echo $type;}}?>  
復制代碼

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/387106.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/387106.shtml
英文地址,請注明出處:http://en.pswp.cn/news/387106.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

09 類的繼承

繼承一個類 class Person(object): def __init__(self, name, gender): self.name name self.gender gender class Student(Person): def __init__(self, name, gender, score): super(Student, self).__init__(name, gender) self.score score 判斷類型 isinstance()可以…

vue 中v-if 與v-show 的區別

相同點或者說功能&#xff0c;都可以動態操作dom元素的顯示隱藏 不同點&#xff1a; 1.手段&#xff1a;v-if是動態的向DOM樹內添加或者刪除DOM元素&#xff1b;v-show是通過設置DOM元素的display樣式屬性控制顯隱&#xff1b;2.編譯過程&#xff1a;v-if切換有一個局部編譯/卸…

vue打包后放在 nginx部署時候的配置文件

部署了三套程序,默認的&#xff0c;admin和design#user nobody; worker_processes 1;#error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info;#pid logs/nginx.pid;events {worker_connections 1024; }http {include …

淘淘商城之技術選型、開發工具和環境、人員配置

一、技術選型 1&#xff09;Spring、SpringMVC、Mybatis 2&#xff09;JSP、JSTL、jQuery、jQuery plugin、EasyUI、KindEditor&#xff08;富文本編輯器&#xff09;、CSSDIV 3&#xff09;Redis&#xff08;緩存服務器&#xff09; 4&#xff09;Solr&#xff08;搜索&#x…

啟動代碼格式:nginx安裝目錄地址 -c nginx配置文件地址

啟動啟動代碼格式&#xff1a;nginx安裝目錄地址 -c nginx配置文件地址 例如&#xff1a;[rootLinuxServer sbin]# /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf停止nginx的停止有三種方式&#xff1a; 從容停止1、查看進程號[rootLinuxServer ~]# ps -ef…

Lecture 3 Divide and Conquer

1.Divide the problem(instance) into one or more sub-problem; 2.Conquer each sub-problem recursively; 3.Combine solutions.

Maven報錯找不到jre

富人之所以越來越富&#xff0c;窮人之所以越來越窮&#xff0c;中產階級之所以總是在債務泥潭中掙扎&#xff0c;其主要原因之一在于他們對金錢的觀念不是來自學校&#xff0c;而是來自家庭。 ---《窮爸爸富爸爸》 一、報錯提示 常規配置maven環境變量&#xff0c;報錯&#x…

vue按照url地址訪問出錯404

問題描述&#xff1a; 最近在開發cms的時候使用Vue.js框架&#xff0c;利用vue-route結合webpack編寫了一個單頁路由項目&#xff0c;自己在服務器端配置nginx。部署完成后&#xff0c;訪問沒問題&#xff0c;從頁面中點擊跳轉也沒問題&#xff0c;但是只要點擊刷新或通過瀏覽器…

Lecture 4 Quick Sort and Randomized Quick Sort

Quick Sort --Divide and Conquer --Sorts “in place” --Very practical with tuning Divide and Conquer: 1.Divide: Partition array into 2 sub-arrays around pivot x such that elements in lower sub-array < x < elements in upper sub-array; 2.Conquer: …

HDU 3966 樹鏈剖分后線段樹維護

題意: 一棵樹, 操作1.$path(a,b)$之間的點權$k$ 操作2.單點查詢 題解: 樹鏈剖分即可,注意代碼細節,雙向映射 主要是記錄一下板子 #include <string.h> #include <stdio.h> #include <algorithm> #define endl \n #define ll long long #define ull unsigned …

VUE config/index.js文件配置

&#xfeff;&#xfeff; 當我們需要和后臺分離部署的時候&#xff0c;必須配置config/index.js: 用vue-cli 自動構建的目錄里面 &#xff08;環境變量及其基本變量的配置&#xff09;123456789101112131415var path require(path)module.exports {build: {index: path.res…

數據規則列表加導入導出

1.進入bos&#xff0c;打開數據規則&#xff0c;進入列表菜單 2.點擊事件-新增操作 3.點擊新增 4.點擊操作類型&#xff0c;輸入%引入 5.點擊確定&#xff0c;保存后生效&#xff0c;導出 、引入模板設置同理轉載于:https://www.cnblogs.com/RogerLu/p/10643521.html

Lecture 6 Order Statistics

Given n elements in array, find kth smallest element (element of rank k) Worst-case linear time order statistics --by Blum, Floyd, Pratt, Rivest, Tarjan --idea: generate good pivot recursively. Not so hot, because the constant is pretty big.

C++ qsort() 函數調用時實參與形參不兼容的問題解決

《劍指OFFER》刷題筆記 —— 撲克牌順子 LL今天心情特別好,因為他去買了一副撲克牌,發現里面居然有2個大王,2個小王(一副牌原本是54張^_^)...他隨機從中抽出了5張牌,想測測自己的手氣,看看能不能抽到順子,如果抽到的話,他決定去買體育彩票,嘿嘿&#xff01;&#xff01;“紅心A…

linux jenkins部署之路之,ftp部署怎么匿名還好用咋解決思密達

怎么安裝就不說了&#xff0c;網上一堆 這噶搭是配置 目錄是/etc/vsftpd/vsftpd.conf # Example config file /etc/vsftpd/vsftpd.conf# # The default compiled in settings are fairly paranoid. This sample file # loosens things up a bit, to make the ftp daemon more u…

powerCat進行常規tcp端口轉發

實戰中&#xff0c;我們也會遇到需要我們進行端口轉發的情況&#xff0c;比如已經拿下的目標機1是在dmz區&#xff0c;而目標1所在內網的其他目標只能通過目標1去訪問&#xff0c;這時候我們就需要端口轉發或者代理來進行后滲透。這次就要介紹一個加強版的nc&#xff0c;基于po…

Lecture 7 Hashing Table I

Hash |---Hash function: Division, Multiplication |---Collision: Chaining, Open addressing(Linear,Double hasing) Symbol-table problem: Table S holding n records pointer --> key|satelite data (record) Hashing: Hash function h maps keys “randomly”…

SpringCloud 微服務

一微服務架構概述1.1 微服務特性以及優點每個服務可以獨立運行在自己的進程里一系列獨立運行的微服務(goods,order,pay,user,search…)共同構建了整個系統每個服務為獨立的業務開發&#xff0c;一個微服務只關注某個特定的功能&#xff0c;例如用戶管理&#xff0c;商品管理微服…

window起別名

http://www.bagualu.net/wordpress/archives/1714 轉載于:https://www.cnblogs.com/wei-huan/p/10654026.html