利用tinify顯示圖片壓縮功能

項(xiàng)目需求

需要在input標(biāo)簽上傳圖片文件時(shí),能夠先經(jīng)過壓縮,然后在上傳到遠(yuǎn)程服務(wù)器,以減少服務(wù)器內(nèi)存的占用。經(jīng)過調(diào)研,發(fā)現(xiàn) tinify 在眾多圖片壓縮中,效果比較好。

使用方法

申請(qǐng)ApiKey

通過郵箱申請(qǐng)賬號(hào),獲取 ApiKey

設(shè)置本地開發(fā)環(huán)境

tinify 開發(fā)文檔中有說明,所有的請(qǐng)求都要通過 HTTPS 連接進(jìn)行。那么問題來了,本地開發(fā)環(huán)境是localhost 或者 127.0.0.1啊,是 HTTP連接,怎么辦呢?

直接上,強(qiáng)行請(qǐng)求的結(jié)果是 404

錯(cuò)誤提示

將本地的 http 請(qǐng)求變成 https 請(qǐng)求,搞這個(gè)還是有些費(fèi)時(shí)間的,我嘗試了nginx做代理,但是奈何不懂用法的含義,不知道為什么沒有效果,還是要好好研究一下 nginx 使用方法。

然后我就換了另外一種方法,也是比較簡(jiǎn)單的。參考原文 Calling HTTPS URLs from http://localhost

在 ~ .zshrc (如果你用的是oh my zsh) 中加入下面這一行配置,然后 source .zshrc使配置生效。然后在命令行輸入chrome 自動(dòng)打開一個(gè)頁(yè)面,然后就可以發(fā)送請(qǐng)求了。

alias chrome=”/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --disable-web-security --user-data-dir=~/.chrome-disable-web-security”

調(diào)用api

項(xiàng)目是基于 angular 的,url 是壓縮后圖片的連接,type 是壓縮后圖片的類型

 compress(file: File | Blob, apiKey: string): Observable<{url: string, type: string}> {
        const headers = new Headers();
        const key = btoa(`api:${apiKey}`);
        headers.append('Authorization', `Basic ${key}`);
        return this.http.post('https://api.tinify.com/shrink', file, { headers }).map(resp => {
            const data = resp.json();
            return {
                url: data.output.url,
                type: data.output.type
            };
        });
    }

從圖片連接獲取到 File

關(guān)鍵在于,請(qǐng)求圖片時(shí),設(shè)置responseType 為 ArrayBuffer類型

 getCompressImage(url: string, type: string, apiKey: string): Observable<File> {
        const headers = new Headers();
        const key = btoa(`api:${apiKey}`);
        headers.append('Authorization', `Basic ${key}`);
        return this.http.get(url, { headers: headers, responseType: ResponseContentType.ArrayBuffer }).map(resp => {
            return new File([resp.arrayBuffer()], 'result.png', { type: type });
        });
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容