经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » HTML/CSS » HTML5 » 查看文章
HTML5 和小程序实现拍照图片旋转、压缩和上传功能
来源:jb51  时间:2018/10/10 8:47:48  对本文有异议

原文地址: github.com/whinc/blog/…

最近接到一个“发表评论”的需求:用户输入评论并且可以拍照或从相册选择图片上传,即支持图文评论。需要同时在 H5 和小程序两端实现,该需求处理图片的地方较多,本文对 H5 端的图片处理实践做一个小结。项目代码基于 Vue 框架,为了避免受框架影响,我将代码全部改为原生 API 的实现方式进行说明,同时项目代码中有很多其他额外的细节和功能(预览、裁剪、上传进度等)在这里都省去,只介绍与图片处理相关的关键思路和代码。小程序的实现方式与 H5 类似,不再重述,在文末附上小程序端的实现代码。

拍照

使用 <input> 标签, type 设为 "file" 选择文件, accept 设为 "image/*" 选择文件为图片类型和相机拍摄,设置 multiple 支持多选。监听 change 事件拿到选中的文件列表,每个文件都是一个 Blob 类型。

  1. <input type="file" accept="image/*" multiple />
  2. <img class="preivew" />
  3. <script type="text/javascript">
  4. function onFileChange (event) {
  5. const files = Array.prototype.slice.call(event.target.files)
  6. files.forEach(file => console.log('file name:', file.name))
  7. }
  8. document.querySelector('input').addEventListener('change', onFileChange)
  9. </script>

图片预览

URL.createObjectURL 方法可创建一个本地的 URL 路径指向本地资源对象,下面使用该接口创建所选图片的地址并展示。

  1. function onFileChange (event) {
  2. const files = Array.prototype.slice.call(event.target.files)
  3.  
  4. const file = files[0]
  5. document.querySelector('img').src = window.URL.createObjectURL(file)
  6. }

图片旋转

通过相机拍摄的图片,由于拍摄时手持相机的方向问题,导致拍摄的图片可能存在旋转,需要进行纠正。纠正旋转需要知道图片的旋转信息,这里借助了一个叫 exif-js 的库,该库可以读取图片的 EXIF 元数据,其中包括拍摄时相机的方向,根据这个方向可以推算出图片的旋转信息。

下面是 EXIF 旋转标志位,总共有 8 种,但是通过相机拍摄时只能产生1、3、6、8 四种,分别对应相机正常、顺时针旋转180°、逆时针旋转90°、顺时针旋转90°时所拍摄的照片。

所以纠正图片旋转角度,只要读取图片的 EXIF 旋转标志位,判断旋转角度,在画布上对图片进行旋转后,重新导出新的图片即可。其中关于画布的旋转操作可以参考 canvas 图像旋转与翻转姿势解锁 这篇文章。下面函数实现了对图片文件进行旋转角度纠正,接收一个图片文件,返回纠正后的新图片文件。

  1. /**
  2. * 修正图片旋转角度问题
  3. * @param {file} 原图片
  4. * @return {Promise} resolved promise 返回纠正后的新图片
  5. */
  6. function fixImageOrientation (file) {
  7. return new Promise((resolve, reject) => {
  8. // 获取图片
  9. const img = new Image();
  10. img.src = window.URL.createObjectURL(file);
  11. img.onerror = () => resolve(file);
  12. img.onload = () => {
  13. // 获取图片元数据(EXIF 变量是引入的 exif-js 库暴露的全局变量)
  14. EXIF.getData(img, function() {
  15. // 获取图片旋转标志位
  16. var orientation = EXIF.getTag(this, "Orientation");
  17. // 根据旋转角度,在画布上对图片进行旋转
  18. if (orientation === 3 || orientation === 6 || orientation === 8) {
  19. const canvas = document.createElement("canvas");
  20. const ctx = canvas.getContext("2d");
  21. switch (orientation) {
  22. case 3: // 旋转180°
  23. canvas.width = img.width;
  24. canvas.height = img.height;
  25. ctx.rotate((180 * Math.PI) / 180);
  26. ctx.drawImage(img, -img.width, -img.height, img.width, img.height);
  27. break;
  28. case 6: // 旋转90°
  29. canvas.width = img.height;
  30. canvas.height = img.width;
  31. ctx.rotate((90 * Math.PI) / 180);
  32. ctx.drawImage(img, 0, -img.height, img.width, img.height);
  33. break;
  34. case 8: // 旋转-90°
  35. canvas.width = img.height;
  36. canvas.height = img.width;
  37. ctx.rotate((-90 * Math.PI) / 180);
  38. ctx.drawImage(img, -img.width, 0, img.width, img.height);
  39. break;
  40. }
  41. // 返回新图片
  42. canvas.toBlob(file => resolve(file), 'image/jpeg', 0.92)
  43. } else {
  44. return resolve(file);
  45. }
  46. });
  47. };
  48. });
  49. }

图片压缩

现在的手机拍照效果越来越好,随之而来的是图片大小的上升,动不动就几MB甚至十几MB,直接上传原图,速度慢容易上传失败,而且后台对请求体的大小也有限制,后续加载图片展示也会比较慢。如果前端对图片进行压缩后上传,可以解决这些问题。

下面函数实现了对图片的压缩,原理是在画布上绘制缩放后的图片,最终从画布导出压缩后的图片。方法中有两处可以对图片进行压缩控制:一处是控制图片的缩放比;另一处是控制导出图片的质量。

  1. /**
  2. * 压缩图片
  3. * @param {file} 输入图片
  4. * @returns {Promise} resolved promise 返回压缩后的新图片
  5. */
  6. function compressImage(file) {
  7. return new Promise((resolve, reject) => {
  8. // 获取图片(加载图片是为了获取图片的宽高)
  9. const img = new Image();
  10. img.src = window.URL.createObjectURL(file);
  11. img.onerror = error => reject(error);
  12. img.onload = () => {
  13. // 画布宽高
  14. const canvasWidth = document.documentElement.clientWidth * window.devicePixelRatio;
  15. const canvasHeight = document.documentElement.clientHeight * window.devicePixelRatio;
  16. // 计算缩放因子
  17. // 这里我取水平和垂直方向缩放因子较大的作为缩放因子,这样可以保证图片内容全部可见
  18. const scaleX = canvasWidth / img.width;
  19. const scaleY = canvasHeight / img.height;
  20. const scale = Math.min(scaleX, scaleY);
  21. // 将原始图片按缩放因子缩放后,绘制到画布上
  22. const canvas = document.createElement('canvas');
  23. const ctx = canvas.getContext("2d");
  24. canvas.width = canvasWidth;
  25. canvas.height = canvasHeight;
  26. const imageWidth = img.width * scale;
  27. const imageHeight = img.height * scale;
  28. const dx = (canvasWidth - imageWidth) / 2;
  29. const dy = (canvasHeight - imageHeight) / 2;
  30. ctx.drawImage(img, dx, dy, imageWidth, imageHeight);
  31. // 导出新图片
  32. // 指定图片 MIME 类型为 'image/jpeg', 通过 quality 控制导出的图片质量,进行实现图片的压缩
  33. const quality = 0.92
  34. canvas.toBlob(file => resolve(tempFile), "image/jpeg", quality);
  35. };
  36. });
  37. },

 

图片上传

通过 FormData 创建表单数据,发起 ajax POST 请求即可,下面函数实现了上传文件。

注意:发送 FormData 数据时,浏览器会自动设置 Content-Type 为合适的值,无需再设置 Content-Type ,否则反而会报错,因为 HTTP 请求体分隔符 boundary 是浏览器生成的,无法手动设置。

  1. /**
  2. * 上传文件
  3. * @param {File} file 待上传文件
  4. * @returns {Promise} 上传成功返回 resolved promise,否则返回 rejected promise
  5. */
  6. function uploadFile (file) {
  7. return new Promise((resolve, reject) => {
  8. // 准备表单数据
  9. const formData = new FormData()
  10. formData.append('file', file)
  11. // 提交请求
  12. const xhr = new XMLHttpRequest()
  13. xhr.open('POST', uploadUrl)
  14. xhr.onreadystatechange = function () {
  15. if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
  16. resolve(JSON.parse(this.responseText))
  17. } else {
  18. reject(this.responseText)
  19. }
  20. }
  21. xhr.send(formData)
  22. })
  23. }

 

小结

有了上面这些辅助函数,处理起来就简单多了,最终调用代码如下:

  1. function onFileChange (event) {
  2. const files = Array.prototype.slice.call(event.target.files)
  3. const file = files[0]
  4. // 修正图片旋转
  5. fixImageOrientation(file).then(file2 => {
  6. // 创建预览图片
  7. document.querySelector('img').src = window.URL.createObjectURL(file2)
  8. // 压缩
  9. return compressImage(file2)
  10. }).then(file3 => {
  11. // 更新预览图片
  12. document.querySelector('img').src = window.URL.createObjectURL(file3)
  13. // 上传
  14. return uploadFile(file3)
  15. }).then(data => {
  16. console.log('上传成功')
  17. }).catch(error => {
  18. console.error('上传失败')
  19. })
  20. }

 

H5 提供了处理文件的接口,借助画布可以在浏览器中实现复杂的图片处理,本文总结了移动端 H5 上传图片这个场景下的一些图片处理实践,以后遇到类似的需求可作为部分参考。

附小程序实现参考

  1. // 拍照
  2. wx.chooseImage({
  3. sourceType: ["camera"],
  4. success: ({ tempFiles }) => {
  5. const file = tempFiles[0]
  6. // 处理图片
  7. }
  8. });
  9. /**
  10. * 压缩图片
  11. * @param {Object} params
  12. * filePath: String 输入的图片路径
  13. * success: Function 压缩成功时回调,并返回压缩后的新图片路径
  14. * fail: Function 压缩失败时回调
  15. */
  16. compressImage({ filePath, success, fail }) {
  17. // 获取图片宽高
  18. wx.getImageInfo({
  19. src: filePath,
  20. success: ({ width, height }) => {
  21. const systemInfo = wx.getSystemInfoSync();
  22. const canvasWidth = systemInfo.screenWidth;
  23. const canvasHeight = systemInfo.screenHeight;
  24. // 更新画布尺寸
  25. this.setData({ canvasWidth, canvasHeight })
  26. // 计算缩放比例
  27. const scaleX = canvasWidth / width;
  28. const scaleY = canvasHeight / height;
  29. const scale = Math.min(scaleX, scaleY);
  30. const imageWidth = width * scale;
  31. const imageHeight = height * scale;
  32. // 将缩放后的图片绘制到画布
  33. const ctx = wx.createCanvasContext("hidden-canvas");
  34. let dx = (canvasWidth - imageWidth) / 2;
  35. let dy = (canvasHeight - imageHeight) / 2;
  36. ctx.drawImage(filePath, dx, dy, imageWidth, imageHeight);
  37. ctx.draw(false, () => {
  38. // 导出压缩后的图片到临时文件
  39. wx.canvasToTempFilePath({
  40. canvasId: "hidden-canvas",
  41. width: canvasWidth,
  42. height: canvasHeight,
  43. destWidth: canvasWidth,
  44. destHeight: canvasHeight,
  45. fileType: "jpg",
  46. quality: 0.92,
  47. success: ({ tempFilePath }) => {
  48. // 隐藏画布
  49. this.setData({ canvasWidth: 0, canvasHeight: 0 })
  50. // 压缩完成
  51. success({ tempFilePath });
  52. },
  53. fail: error => {
  54. // 隐藏画布
  55. this.setData({ canvasWidth: 0, canvasHeight: 0 })
  56. fail(error);
  57. }
  58. });
  59. });
  60. },
  61. fail: error => {
  62. fail(error);
  63. }
  64. });
  65. }
  66. /**
  67. * 上传文件
  68. */
  69. uploadFile({ uploadUrl, filePath, onData, onError }) {
  70. wx.uploadFile({
  71. url: uploadUrl
  72. filePath: filePath,
  73. name: "file",
  74. header: {
  75. Cookie: cookie
  76. },
  77. success: res => {
  78. if (res.statusCode === 200) {
  79. onData(res.data)
  80. } else {
  81. onError(res);
  82. }
  83. },
  84. fail: error => {
  85. onError(error);
  86. }
  87. });
  88. }

总结

以上所述是小编给大家介绍的HTML5 和小程序实现拍照图片旋转、压缩和上传功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对w3xue网站的支持!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号