亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我如何從文件閱讀器返回調整大小的圖像

我如何從文件閱讀器返回調整大小的圖像

慕婉清6462132 2021-10-29 10:54:37
我創建了一個負責調整圖像大小的函數,現在我想從函數返回調整大小的圖像。我正在使用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)}   />我想返回新創建的圖像。
查看完整描述

2 回答

?
嗶嗶one

TA貢獻1854條經驗 獲得超8個贊

你可以使用 Promise 解決這個問題,


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


  return new Promise((resolve, reject) => {


    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) => {

          resolve(new File([blob], fileName, {

            type: 'image/jpeg',

            lastModified: Date.now()

          }));

        }, 'image/jpeg', 1);

      };

    };

  });

}

隨著async, await,


async function handleUpload(e: IHTMLInputEvent) {

  const resizedImage = await resizeImage(e, 600);


  // do you suff here

}

JSX,


<input 

   className={classes.inputForUpload} 

   accept='image/*' 

   type='file' 

   ref={uploadImage} 

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

/>


查看完整回答
反對 回復 2021-10-29
?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

請問您為什么不喜歡使用狀態的解決方案?這似乎是一個非常標準的用例。


您的狀態可能如下所示:


state = {

  imageDescription: '',

  imageUrl: null

};

您的操作處理程序將在成功時簡單地設置狀態,如下所示:


img.onload = () => {

  ...


  this.setState({ imageDescription: fileName, imageSrc: img.src })

};

最后你的渲染函數看起來像這樣:


render() {

  const { imageDescription, imageUrl } = this.state;


  return (

    <Fragment>

       <input 

         className={classes.inputForUpload} 

         accept='image/*' 

         type='file' 

         ref={uploadImage} 

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

       />

       <img src={imageUrl} alt={imageDescription} />

    </Fragment>

  )

}

PS你可以刪除handleUpload,直接調用resizeImage。


查看完整回答
反對 回復 2021-10-29
  • 2 回答
  • 0 關注
  • 183 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號