Skip to content

Commit

Permalink
fix(useimage): fix compressor track due to toBlob error
Browse files Browse the repository at this point in the history
  • Loading branch information
innocces committed Mar 21, 2022
1 parent 13df359 commit f320557
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 14 deletions.
2 changes: 1 addition & 1 deletion packages/hooks/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
],
"dependencies": {
"@babel/runtime": "^7.14.6",
"compressorjs": "^1.0.7",
"compressorjs-global": "^1.1.1",
"lodash-wechat": "^1.0.0",
"lodash.uniq": "^4.5.0",
"querystring": "^0.2.1"
Expand Down
15 changes: 2 additions & 13 deletions packages/hooks/src/useImage/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,8 @@ import Taro, {
chooseMessageFile,
} from '@tarojs/taro';
import { useCallback, useState } from 'react';
import Compressor from 'compressorjs';
import useEnv from '../useEnv';
import { saveImageForH5, downloadImage, generateBlobUrl } from './utils';
import { saveImageForH5, downloadImage, compressForH5 } from './utils';
import { ENV_TYPE } from '../constant';

export type ChooseImageOption = Partial<
Expand Down Expand Up @@ -193,17 +192,7 @@ function useImage(options: ChooseImageOption): [IFileInfo, IAction] {
try {
if (env === ENV_TYPE.WEB) {
const blob = await downloadImage(src);
new Compressor(blob, {
quality: (quality || 80) / 100,
success: (res) => {
const tempFilePath = generateBlobUrl(res);
resolve({
tempFilePath,
errMsg: 'compressImage:ok',
});
},
error: reject,
});
compressForH5(blob, quality).then(resolve, reject);
} else {
Taro.compressImage({
src,
Expand Down
18 changes: 18 additions & 0 deletions packages/hooks/src/useImage/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import Compressor from 'compressorjs';

export const downloadImage = async (filePath: string) => {
const responese = await fetch(filePath);
const blob = await responese.blob();
Expand Down Expand Up @@ -32,3 +34,19 @@ export const saveImageForH5 = async (filePath: string) => {
}
return false;
};

export const compressForH5 = (blob: Blob, quality?: number) => {
return new Promise((resolve, reject) => {
new Compressor(blob, {
quality: (quality || 80) / 100,
success: (res) => {
const tempFilePath = generateBlobUrl(res);
resolve({
tempFilePath,
errMsg: 'compressImage:ok',
});
},
error: reject,
});
});
};

0 comments on commit f320557

Please # to comment.