search
HomeWeb Front-endH5 TutorialTutorial example of using html5 to process photos on mobile terminal

A while ago, I used Vue to develop a webapp in the company. I met a user who took a picture or called the mobile phone album to display the picture, and then uploaded it to the server. After only half a year of contact with the front-end, I embarked on a road of pitfalls. Let me talk about it below. The pitfalls I encountered!

Summary of various pitfalls

  • Retrieve mobile photo album
    There is no problem with iOS, but Android phones are really pitfalls. I searched a lot of methods online, or there are some. The phone doesn't work. Either it can only adjust the photo album but not the camera, or it can only adjust the camera but not the photo album.

  • Calling the photo album. After getting the photo and rendering it on the interface, iOS appears again. The problem is that the pictures taken by the camera are rotated 90 degrees, or the normal pictures on Apple are rotated 90 degrees when displayed on Android phones, and some pictures that are normal on Apple are distorted in the background. As an iOS developer, I don't understand this. After several investigations, I came to the conclusion that Apple's camera is crooked!

  • The browser will crash after the image is rendered, especially on WeChat. I have to say that WeChat is so tricky. All kinds of problems will occur when anything is uploaded to WeChat!

  • Then there is the problem of image uploading. At first, it was in the form of file upload. Later, the test results showed that many Android machines could not upload successfully! If you say too much, you will shed tears. If you don’t say too much, let’s get to the point!

Summarize my solution, I hope it can be helpful to people who are still newbies like me

Recall the mobile photo album and camera

Although using h5 to call the photo album is a sentence to call from the web page, if you want to call the photo album and the camera, you have to write like this (I really checked it for a long time)

<form id="uploadForm" enctype="multipart/form-data">
   <input class="upload-open-photo" accept="image/*" type="file" id="filechooser" v-on:change="btnUploadFile($event)"/>
</form>

Picture rendering

I used canvas for image rendering, and used a plug-in called exif.js to get the direction of the mobile phone shooting (that is, whether to hold the mobile phone vertically or horizontally when taking pictures), and then judge the device. For iOS devices, three Rotate the picture in the direction and use canvas to draw it on the canvas

btnUploadFile(e){
      //获取图片
      var  self = this;
      var filechooser = document.getElementById(&#39;filechooser&#39;);
      var previewer = document.getElementById(&#39;previewer&#39;);
      var that = e.target;
      var files = that.files;
      var file = files[0];
      //判断拍摄方向,
       EXIF.getData(file,function(){
            self.orientation=EXIF.getTag(this,&#39;Orientation&#39;);
       });
      self.fileData = file;
       // 接受 jpeg, jpg, png 类型的图片
       if (!/\/(?:jpeg|jpg|png)/i.test(file.type)){
             return;
      }
      var reader = new FileReader();
     reader.onload = function() {
          var result = this.result;
          var img =  new Image();
         //进行图片的渲染
           img.onload = function() {
                //图片旋转压缩处理后的base64
                var compressedDataUrl =self.compress(img,self.fileData.type);
               //渲染到img标签上
                self.toPreviewer(compressedDataUrl);
               img = null;
           };
         img.src = result;
      };
      reader.readAsDataURL(self.fileData);
},

Picture rendering

When rendering the picture, you not only need to rotate the picture, but also compress it. Because the current camera pixels are too high, high-definition pictures It will cause the browser to crash. Of course, if you are doing WeChat development and you only need to adapt it in the WeChat browser, you can refer to the method of calling the photo album in WeChat jssdk, so that there will be no problems with picture distortion and crash. Of course, if we are not just doing WeChat, we still have to compress it, also using canvas
(mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html)

//对图片进行旋转,压缩的方法,最终返回base64  渲染给img标签的src
compress(img, fileType) {
      var degree=0,drawWidth,drawHeight,width,height;
      drawWidth=img.width;
      drawHeight=img.height;
      //以下改变一下图片大小
     var maxSide = Math.max(drawWidth, drawHeight);
     if (maxSide > 1024) {
           var minSide = Math.min(drawWidth, drawHeight);
            minSide = minSide / maxSide * 1024;
            maxSide = 1024;
           if (drawWidth > drawHeight) {
                drawWidth = maxSide;
                drawHeight = minSide;
            } else {
                drawWidth = minSide;
                drawHeight = maxSide;
            }
    }
    var canvas=document.createElement(&#39;canvas&#39;);
    canvas.width=width=drawWidth;
    canvas.height=height=drawHeight;
    var context=canvas.getContext(&#39;2d&#39;);
    //判断图片方向,重置canvas大小,确定旋转角度,iphone默认的是home键在右方的横屏拍摄方式
    if($.device.ios){
         switch(this.orientation){
              //iphone横屏拍摄,此时home键在左侧
             case 3:
                   degree=180;
                   drawWidth=-width;
                   drawHeight=-height;
                    break;
          //iphone竖屏拍摄,此时home键在下方(正常拿手机的方向)
              case 6:
                    canvas.width=height;
                    canvas.height=width;
                    degree=90;
                    drawWidth=width;
                    drawHeight=-height;
                    break;
              //iphone竖屏拍摄,此时home键在上方
               case 8:
                      canvas.width=height;
                       canvas.height=width;
                       degree=270;
                       drawWidth=-width;
                       drawHeight=height;
                       break;
          }
     }
     //使用canvas旋转校正
     context.rotate(degree*Math.PI/180);
     context.drawImage(img,0,0,drawWidth,drawHeight);
     // 压缩0.5就是压缩百分之50
     var base64data = canvas.toDataURL(fileType, 0.5);
     canvas = context = null;
     this.urlbase = base64data;
      return base64data;
},

Finally get the base64 rendering to The src of the img tag

toPreviewer(dataUrl) {
       previewer.src = dataUrl;
 },

Image upload

The base64 obtained above provides an interface for base64 to upload images. The advantage of base64 is that the base64 we obtain is the base64 of the rotated and compressed image. , so that when we upload the image to the server or display it from other places, it will be rotated and compressed. If other pages want to display this image, the process of rotation and compression will be omitted! In fact, I still don’t know why some Android devices can’t upload images through file transfer, but after successfully changing the base64 upload method, I no longer have to worry about finding a job.

I feel like I have stepped on a lot of pitfalls. In the final analysis, I still lack front-end experience!

【Related recommendations】

1. Free h5 online video tutorial

2. HTML5 full version manual

3. php.cn original html5 video tutorial

The above is the detailed content of Tutorial example of using html5 to process photos on mobile terminal. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool