Table of Contents
2. About the selection preview function
3. Obtain the extension of the file uploaded
4. Obtaining the ios photo direction
5.ios photo direction correction
Home Web Front-end H5 Tutorial H5 uses react components to take pictures and select pictures to upload

H5 uses react components to take pictures and select pictures to upload

Dec 31, 2018 am 09:45 AM
html5 javascript react.js

The content of this article is about H5 using react components to take pictures and select pictures to upload. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The project was restructured some time ago and changed to an SSR project, but the image selection upload component used before did not support SSR (server-side-render). So I conducted research and found many tools. But some are too big, some are troublesome to use, and some do not meet the needs of use. Decided to write an h5 mobile image upload component myself. Image uploading is a relatively common requirement. The PC version is fine, but the mobile version is not particularly easy to do. Below we briefly record some key issues in the process.

Key points

1. About input

The selection function is implemented using the tag. Attribute accept='image/*', :capture means that the system's default device can be captured, such as: camera--camera; camcorder--camera; microphone--recording. If capture="camera" is set, the camera will be used by default. There is a problem that some models cannot call the camera, so we will not set it here. Allows multiple selections, plus a callback function for the onchange event. The final input probably looks like this:

<input type=&#39;file&#39;
    className={classes.picker}
    accept=&#39;image/*&#39;
    multiple
    capture="camera"
    onChange={this.onfileChange} />
Copy after login

Of course, this input is ugly. We can overwrite it with the selection button style we need by setting `opacity:0` and positioning it. Make it a little more glamorous.

2. About the selection preview function

Being able to preview after selecting a picture is a common function. Let’s put aside the style here and only talk about the code implementation. In the callback function of onchange, we can get the selected file through e.target.files, but the file cannot be displayed on the page. The usual method is to use reader.readAsDataURL(file) to convert it to base64 and then display it on the page. superior. I use a nine-square grid display here, and each picture is a canvas. Considering the issue of different picture aspect ratios, I first get the base64 file through reader.readAsDataURL(file). Then create an image drawn through the canvas aspect ratio of the nine-square grid, so that the image content can cover the entire canvas without distortion.

fileToCanvas (file, index) {//文件
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (event) => {
            let image = new Image();
            image.src = event.target.result;
            image.onload = () => {
                let imageCanvas = this['canvas' + index].getContext('2d');
                let canvas = { width: imageCanvas.canvas.scrollWidth * 2, height: imageCanvas.canvas.scrollHeight * 2 };
                let ratio = image.width / image.height;
                let canvasRatio = canvas.width / canvas.height;
                let xStart = 0; let yStart = 0; let renderableWidth; let renderableHeight;
                if (ratio > canvasRatio) { 
                // 横向过大,以高为准,缩放宽度
                    let hRatio = image.height / canvas.height;
                    renderableHeight = image.height;
                    renderableWidth = canvas.width * hRatio;
                    xStart = (image.width - renderableWidth) / 2;
                }
                if (ratio < canvasRatio) { 
                // 横向过小,以宽为准,缩放高度
                    let wRatio = image.width / canvas.width;
                    renderableWidth = image.width;
                    renderableHeight = canvas.height * wRatio;
                    yStart = (image.height - renderableHeight) / 2;
                }
                imageCanvas.drawImage(image, xStart, yStart, renderableWidth, renderableHeight, 0, 0, canvas.width * 2, canvas.height);
            };
        };
    }
Copy after login

3. Obtain the extension of the file uploaded

When taking pictures on some models, the file obtained through the onchange event is blob (Xiaomi 6, etc.) at this time blob.type Manually determine the extension.

4. Obtaining the ios photo direction

When the ios photo is uploaded, it is found that the file has been rotated. The local file is indeed normal. The cause of this problem will not be explained in detail here. If you are interested, you can search it. So we need to detect the orientation and rotate the image back to the normal orientation. There are many ready-made libraries for obtaining orientation, such as Exif.js. But this library is a bit large, and it doesn’t seem worth introducing it for this small requirement. There are many ready-made codes for getting the image direction on stackoverflow.
Slightly modified:

getOrientation (file) {
        return new Promise((resolve, reject) => {
            let reader = new FileReader();
            reader.onload = function (e) {
            //e.target.result为base64编码的文件
                let view = new DataView(e.target.result);
                if (view.getUint16(0, false) !== 0xffd8) {
                    return resolve(-2);
                }
                let length = view.byteLength;
                let offset = 2;
                while (offset < length) {
                    let marker = view.getUint16(offset, false);
                    offset += 2;
                    if (marker === 0xffe1) {
                        let tmp = view.getUint32(offset += 2, false);
                        if (tmp !== 0x45786966) {
                            return resolve(-1);
                        }
                        let little = view.getUint16(offset += 6, false) === 0x4949;
                        offset += view.getUint32(offset + 4, little);
                        let tags = view.getUint16(offset, little);
                        offset += 2;
                        for (let i = 0; i < tags; i++) {
                            if (view.getUint16(offset + i * 12, little) === 0x0112) {
                                return resolve(view.getUint16(offset + i * 12 + 8, little));
                            }
                        }
                    } else if ((marker & 0xff00) !== 0xff00) {
                        break;
                    } else {
                        offset += view.getUint16(offset, false);
                    }
                }
                return resolve(-1);
            };

            reader.readAsArrayBuffer(file.slice(0, 64 * 1024));
        });
    }
Copy after login

//Return value: 1--normal, -2--non-jpg, -1--undefined

5.ios photo direction correction

The normal image orientation should be 1, so we convert the file to canvas and use the transform method of canvas to transform the canvas, please refer to it. Finally, get the base64 image with the normal direction of base64 encoding through canvas.toDataURL(''), and then convert the base64 to blob for upload;

    //重置文件orientation
resetOrientationToBlob (file, orientation) {
    return new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (event) => {
            let image = new Image();
            image.src = event.target.result;
            image.onload = () => {
                let width = image.width;
                let height = image.height;
                let canvas = document.createElement('canvas');
                let ctx = canvas.getContext('2d');
                if (orientation > 4 && orientation < 9) {
                    canvas.width = height;
                    canvas.height = width;
                } else {
                    canvas.width = width;
                    canvas.height = height;
                }

                switch (orientation) {
                case 2:
                    ctx.transform(-1, 0, 0, 1, width, 0);
                    break;
                case 3:
                    ctx.transform(-1, 0, 0, -1, width, height);
                    break;
                case 4:
                    ctx.transform(1, 0, 0, -1, 0, height);
                    break;
                case 5:
                    ctx.transform(0, 1, 1, 0, 0, 0);
                    break;
                case 6:
                    ctx.transform(0, 1, -1, 0, height, 0);
                    break;
                case 7:
                    ctx.transform(0, -1, -1, 0, height, width);
                    break;
                case 8:
                    ctx.transform(0, -1, 1, 0, 0, width);
                    break;
                default:
                    ctx.transform(1, 0, 0, 1, 0, 0);
                }

                ctx.drawImage(image, 0, 0, width, height);
                let base64 = canvas.toDataURL('image/png');
                let blob = this.dataURLtoBlob(base64);
                resolve(blob);
            };
        };
    });
}
Copy after login

Finally

image Uploading, this part should be relatively easy. Just upload the file in the form of FormData. The above code is only the pseudo code of some functions and is not the final implementation of all functions.

Just toss around if you can, and in the end you will find that you have learned a lot, but other people's wheels are still useful2333.


The above is the detailed content of H5 uses react components to take pictures and select pictures to upload. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles