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

不言
不言forward
2018-12-31 09:45:407967browse

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} />

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);
            };
        };
    }

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));
        });
    }

//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);
            };
        };
    });
}

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:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete