我如何从文件阅读器返回调整大小的图像

我创建了一个负责调整图像大小的函数,现在我想从函数返回调整大小的图像。


我正在使用react并且知道我可以通过使用来解决问题,state但我不喜欢这个解决方案..


尝试返回每个不同的范围,但我仍然收到undefined回复。此外,当我返回reader本身时,我会得到旧数据。


界面


   interface IHTMLInputEvent extends Event {

        target: HTMLInputElement & EventTarget;

    }

调整大小功能


function resizeImage(file: IHTMLInputEvent, width: number) {


        const fileName = file.target.files[0].name;

        const reader = new FileReader();


        reader.readAsDataURL(file.target.files[0]);


        reader.onload = (event) => {

            const img = new Image();

            img.src = event.target.result.toString();


            img.onload = () => {

                const elem = document.createElement('canvas');

                const scaleFactor = width / img.width;

                elem.width = width;

                elem.height = img.height * scaleFactor;


                const ctx = elem.getContext('2d');

                ctx.drawImage(img, 0, 0, width, img.height * scaleFactor);


                ctx.canvas.toBlob((blob) => {

                    return new File([blob], fileName, { type: 'image/jpeg', lastModified: Date.now() });

                }, 'image/jpeg', 1);

            };

        };

    }


处理上传的功能(到目前为止)


function handleUpload(e: IHTMLInputEvent) {

        const resizedImage = resizeImage(e, 600);

    }

输入栏


 <input 

   className={classes.inputForUpload} 

   accept='image/*' 

   type='file' 

   ref={uploadImage} 

   onChange={(e: IHTMLInputEvent) => handleUpload(e)} 

  />

我想返回新创建的图像。


慕婉清6462132
浏览 162回答 2
2回答

哔哔one

你可以使用 Promise 解决这个问题,function resizeImage(file: IHTMLInputEvent, width: number) {&nbsp; return new Promise((resolve, reject) => {&nbsp; &nbsp; const fileName = file.target.files[0].name;&nbsp; &nbsp; const reader = new FileReader();&nbsp; &nbsp; reader.readAsDataURL(file.target.files[0]);&nbsp; &nbsp; reader.onload = (event) => {&nbsp; &nbsp; &nbsp; const img = new Image();&nbsp; &nbsp; &nbsp; img.src = event.target.result.toString();&nbsp; &nbsp; &nbsp; img.onload = () => {&nbsp; &nbsp; &nbsp; &nbsp; const elem = document.createElement('canvas');&nbsp; &nbsp; &nbsp; &nbsp; const scaleFactor = width / img.width;&nbsp; &nbsp; &nbsp; &nbsp; elem.width = width;&nbsp; &nbsp; &nbsp; &nbsp; elem.height = img.height * scaleFactor;&nbsp; &nbsp; &nbsp; &nbsp; const ctx = elem.getContext('2d');&nbsp; &nbsp; &nbsp; &nbsp; ctx.drawImage(img, 0, 0, width, img.height * scaleFactor);&nbsp; &nbsp; &nbsp; &nbsp; ctx.canvas.toBlob((blob) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve(new File([blob], fileName, {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: 'image/jpeg',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lastModified: Date.now()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }));&nbsp; &nbsp; &nbsp; &nbsp; }, 'image/jpeg', 1);&nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; };&nbsp; });}随着async, await,async function handleUpload(e: IHTMLInputEvent) {&nbsp; const resizedImage = await resizeImage(e, 600);&nbsp; // do you suff here}JSX,<input&nbsp;&nbsp; &nbsp;className={classes.inputForUpload}&nbsp;&nbsp; &nbsp;accept='image/*'&nbsp;&nbsp; &nbsp;type='file'&nbsp;&nbsp; &nbsp;ref={uploadImage}&nbsp;&nbsp; &nbsp;onChange={async (e: IHTMLInputEvent) => await handleUpload(e)}&nbsp;/>

12345678_0001

请问您为什么不喜欢使用状态的解决方案?这似乎是一个非常标准的用例。您的状态可能如下所示:state = {&nbsp; imageDescription: '',&nbsp; imageUrl: null};您的操作处理程序将在成功时简单地设置状态,如下所示:img.onload = () => {&nbsp; ...&nbsp; this.setState({ imageDescription: fileName, imageSrc: img.src })};最后你的渲染函数看起来像这样:render() {&nbsp; const { imageDescription, imageUrl } = this.state;&nbsp; return (&nbsp; &nbsp; <Fragment>&nbsp; &nbsp; &nbsp; &nbsp;<input&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;className={classes.inputForUpload}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;accept='image/*'&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;type='file'&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ref={uploadImage}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;onChange={(e: IHTMLInputEvent) => handleUpload(e)}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;/>&nbsp; &nbsp; &nbsp; &nbsp;<img src={imageUrl} alt={imageDescription} />&nbsp; &nbsp; </Fragment>&nbsp; )}PS你可以删除handleUpload,直接调用resizeImage。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript