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.mzph.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()可以…

启动代码格式: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.

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: …

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.

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;商品管理微服…

vue在ie9中的兼容问题

问题总结 https://github.com/vuejs-templates/webpack/issues/260 首先npm install --save babel-polyfill然后在main.js中的最前面引入babel-polyfillimport babel-polyfill在index.html 加入以下代码&#xff08;非必须&#xff09;<meta http-equiv"X-UA-Compatib…

Lecture 9 Random built Binary Search Trees BSTs

Random built Binary Search Trees BSTs E[hight] near 3logn Quick Sort? Relation to Quick Sort: BST sort & Quick sort make same comparisons but in a different order. Randomized BST Sort: 1. Randomly permute A 2. BST sort(A)

Vue项目中遇到了大文件分片上传的问题

Vue项目中遇到了大文件分片上传的问题&#xff0c;之前用过webuploader&#xff0c;索性就把Vue2.0与webuploader结合起来使用&#xff0c;封装了一个vue的上传组件&#xff0c;使用起来也比较舒爽。 上传就上传吧&#xff0c;为什么搞得那么麻烦&#xff0c;用分片上传&#x…

NDK学习笔记-使用现有so动态库

前面将的都是如何使用C/C文件生成so动态库&#xff0c;那么在使用别人的so动态库的时候应该怎么做呢&#xff1f;这篇文章就是使用一个变声功能的动态库&#xff0c;完成对于以有so动态库的说明。 动态库来源 在互联网中&#xff0c;有着许许多多动态库&#xff0c;很多厂商也对…

Spring cloud系列十四 分布式链路监控Spring Cloud Sleuth

1. 概述 Spring Cloud Sleuth实现对Spring cloud 分布式链路监控 本文介绍了和Sleuth相关的内容&#xff0c;主要内容如下&#xff1a; Spring Cloud Sleuth中的重要术语和意义&#xff1a;Span、Trance、AnnotationZipkin中图形化展示分布式链接监控数据并说明字段意义Spring …