The mobile end uses localResizeIMG4 to compress the image,

Source: Internet
Author: User

The mobile end uses localResizeIMG4 to compress the image,

Mobile h5 development cannot avoid uploading images. Generally, we use the built-in html control to input or useUpload API. However, the upload API is not available anywhere. Using the input upload control provided by html, the image size is too large and the upload is unstable. LocalResizeIMG4 is generated for this purpose.

This document demonstrates the version of localResizeIMG 4.9.35.

Features

Compatible with IOS, Android, PC, and automatic file loading on demand
Compression Ratio supported
Support native JS, jQuery/Zepto
Support Promise features
Use Base64

LocalResizeIMG has four historical versions. The usage of each version may be different. This article takes the latest stable version localResizeIMG4 as an example.

Https://github.com/think2011/localResizeIMG/archive/4.9.35.zip

How to Use

Page Introduction

<script src="./dist/lrz.bundle.js"></script>

Html

<input type="file" capture="camera" accept="image/*" name="logo" id="file">

Capture = "camera" can be taken;
Accept = "image/*" only accept Images

You can use the change event to obtain the selected image.

Use native js

Document. querySelector ('input '). addEventListener ('change', function () {// this. files [0] is the selected file lrz (this. files [0], {width: 1024 }). then (function (rst) {// show the processed Image to the user (optional) var img = new Image (); img. src = rst. base64; // base64 string img. onload = function () {document. body. appendChild (img) ;}; return rst ;}). then (function (rst) {// upload the file to the backend. ================================== = * // Native ajax uploads code, so it looks a lot more, but it can definitely use // other frameworks. For example, jQuery processes formData slightly differently. Please google and baidu on your own. Var xhr = new XMLHttpRequest (); xhr. open ('post', 'HTTP: // localhost: 5000/'); xhr. onload = function () {if (xhr. status = 200) {// upload successful} else {// handle other cases}; xhr. onerror = function () {// handle error}; xhr. upload. onprogress = function (e) {// upload progress var percentComplete = (e. loaded/e. total) | 0) * 100;}; // Add the rst parameter. formData. append ('filelen', rst. fileLen); rst. formData. append ('xxx', 'I am another parameter'); // triggers the upload xhr. send (rst. formData ); /* ===================================================== ================= */return rst ;}). catch (function (err) {// in case of an error, the error message can be captured here // and none of the above then will execute alert (err );}). always (function () {// whether it is a successful failure, it will be executed here });});

ReturnedRstObject Data example:

{Origin: File, base64: "data: image/jpeg; base64,/9j/4 AAQSkZJRgABAQAAAQABAAD... Iigaooooakkkkaciiigaooakkkkaciiigaooakkkkkap/Z ", base64Len: 1507}

Origin:File
LastModified: 1442482311173
LastModifiedDate: Thu Sep 17 2015 17:31:51 GMT + 0800 (China Standard Time)
Name: "upload-add.png"
Size: 291
Type: "image/png"
WebkitRelativePath :""

WhereBase64The attribute is base64 encoded with the image type and can be directly used for the src of the img tag. If the backend needs to convert the attribute value to image storage, the image type must be removed first. The following is an example. Earlier versions of localResizeIMG1 will return bothResult. base64AndResult. clearBase64(Without image encoding ).

Use jQuery/Zepto

$(function(){ $('input[name=logo]').on('change', function(){   lrz(this.files[0], {width: 640})   .then(function (rst) {    $.ajax({     url: site_url + 'api/user/updLogo',     type: 'post',     data: {img: rst.base64},     dataType: 'json',     timeout: 200000,     error: doAjax.error,     success: doAjax.success,    });        })   .catch(function (err) {   })   .always(function () {   }); });});

If your image is not uploaded by the user, you can directly input the image path:

Lrz ('. /xxx/xx/x.png '). then (function (rst) {// execution is successful }). catch (function (err) {// execution fails }). always (function () {// whether it is successful or failed, it will be executed });

Backend processing (PHP)

$ Base64_image_content = $ _ POST ['img ']; if (preg_match ('/^ (data: \ s * image \/(\ w +); base64 ,)/', $ base64_image_content, $ result) {$ type = $ result [2]; // jpeg // remove the image type $ img = base64_decode (str_replace ($ result [1], '', $ base64_image_content); // returns the file stream} // use AliOSS to upload $ url = OSS: upload ($ img, $ type );

$ Result content:

Array( [0] => data:image/jpeg;base64, [1] => data:image/jpeg;base64, [2] => jpeg)

Complete example (HTML + PHP)

Run in a server environment (such as LAMP.

Index.html

<! DOCTYPE html> 

Upload. php

<? Php $ base64_image_content =$ _ POST ['img ']; if (preg_match ('/^ (data: \ s * image \/(\ w +); base64 ,) /', $ base64_image_content, $ result) {$ type = $ result [2]; // jpeg $ img = base64_decode (str_replace ($ result [1], '', $ base64_image_content); // returns the file stream} // var_dump ($ _ POST); // string (1507) "data: image/jpeg; base64, /9j/4AAQSkZJR... // var_dump ($ result); // "data: image/jpeg; base64," "data: image/jpeg; base64, "" jpeg "// var_dump ($ img); // The returned resource is, directly use  to display images/* output to files * // Method 1: directly use file_put_contents $ tmp_file = time (). '. '. $ type; // file_put_contents ($ tmp_file, $ img); // you can directly save the file stream as a local image. // Method 2: convert it to GD image resource first, generate a file or display the output $ im = imagecreatefromstring ($ img); // resource (2) of type (gd) image resource imagejpeg ($ im, $ tmp_file ); // image stream (image) is output to the standard output (browser or file) in JPEG format // or use AliOSS to upload // $ url = OSS: upload ($ img, $ type); return ajaxReturn ($ tmp_file); function ajaxReturn ($ data = array (), $ code = 0, $ msg = 'success ') {$ result = array ('result' => $ data, 'mcm '=> $ code, 'msg' => $ msg,); echo json_encode ($ result ); exit ;}

Sample Code on github: https://github.com/52fhy/localResizeIMG4/tree/master/lrz

Parameter documentation

Parameters

Lrz (file, [options]);

  • File obtained through input: file, or directly input the image path
  • [Options] This parameter can be ignored.
  • Width {Number}: the maximum width of the image. The default value is the source image width. If the height is not set, the width is used.
  • Height {Number} is the same as above
  • Quality {Number} Image Compression quality. value range: 0-1. Default Value: 0.7
  • FieldName {String} field name received by the backend. Default Value: file

Returned results

The returned value isPromiseObject

  • Then (rst)
  • Rst. formData backend data that can be processed
  • Rst. file: the compressed file object (which has been lost in rst. formData by default). Note that if the compression rate is too low, this will be the original file object.
  • The size of the image generated by rst. fileLen. the backend can use this value to verify whether the data is transmitted completely.
  • The base64 encoded image after rst. base64 is generated. The backend can process this string as an image or use it directly for img. src = base64
  • The size of base64 generated by rst. base64Len. the backend can use this value to verify whether the transmission is complete (if base64 is used)
  • Rst. origin is the original file object, which contains information about the original file, such as the size and date.
  • Catch (err)
  • Always ()

Lrz history

Lrz1 is based on jquery. You need to reference jquery. js, localResizeIMG. js, patch/mobileBUGFix. mini. js (client ).
Lrz2, based on native js, is written in Orz using coffeescript. It has a UI and has known bugs.
Lrz3, based on native js, provides pc and mobile versions, fixes bugs and questions, reconstructs the code, removes the UI, and serves only as a pure tool for secondary development.
Lrz4, based on native js, has been upgraded to a stable version and is recommended.
Lrz Principle

The basic principle is to render the image through canvas, and then compress and save it as a base64 string (the image can be compiled into jpg format) using the toDataURL method ).

For details, see WIKI.

How to customize upload buttons

The default upload button is not good, and Android and iPhone are different. Need to be unified:

The principle is to use the background image to set the transparency of the input to 0.

<div style="background:url(images/upload-add.png) no-repeat right/40px;">  <input type="file" capture="camera" accept="image/*" name="logo" id="file" class="selectinput" style="width:100%;opacity:.01"></div>

1. php reads and saves base64 encoded image content-fxhover's personal space-Open Source China Community

2. Parameter documentation · think2011/localResizeIMG Wiki
Https://github.com/think2011/localResizeIMG/wiki

3. think2011/localResizeIMG: the front-end local client compresses images, and is compatible with IOS, Android, PC, and automatic file loading on demand.
Https://github.com/think2011/localResizeIMG

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.