Online Preview and compression of A Single Image

Source: Internet
Author: User

This method has not tested the browser compatibility and has only been tested on Google.

Online Preview of images: The general idea is to obtain the absolute path of the file and assign the path to SRC to implement Online Preview. However, in reality, browsers, especially high-version browsers, are subject to user security considerations, developers are not allowed to obtain the absolute path through file. Therefore, the canvas function in H5 is used to re-paint the image and obtain the base64-encoded dataurl, then assign this address to SRC for online preview.

Image compression principle: Modify the size of a large image according to the predefined size.

<! Doctype HTML> <HTML lang = "en"> // Interesting logic for processing images based on width and height. You can think about it. Image. onload = function () {var W = 1000; var H = 1000; var nw = This. naturalwidth; var nH = This. naturalheight; var targetw = 0; var targeth = 0; If (NW> NH) {If (NW> W) {targetw = W;} else {targetw = NW ;} targeth = NH/nw * targetw;} else {If (NH> H) {targeth = H;} else {targeth = nH;} targetw = targeth/NH * NW ;} vaR CVS = document. createelement ('canvas '); var CTX = CVs. getcontext ("2D"); CVs. width = targetw; CVs. height = targeth; CTX. drawimage (image, 0, 0, NW, NH, 0, 0, CVS. width, CVS. height); var newimagedata = CVs. todataurl ("image/JPEG"); // $ (". userhead "). val (newimagedata. split ("base64,") [1]);} reader. onload = function (e) {$ ("# imginp "). ATTR ("src" ,e.tar get. result); image. src = e.tar get. result;}; reader. readasdataurl (f) ;}</SCRIPT> 

 

Online Preview and compression of A Single Image

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.