Skip to content

Commit

Permalink
improvement(useimage): add compressImage for h5
Browse files Browse the repository at this point in the history
  • Loading branch information
innocces committed Jul 28, 2021
1 parent 4d6979a commit 12fb4c4
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 9 deletions.
5 changes: 4 additions & 1 deletion packages/hooks/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,8 @@
"engines": {
"node": ">=12.0.0"
},
"license": "MIT"
"license": "MIT",
"devDependencies": {
"compressorjs": "^1.0.7"
}
}
17 changes: 15 additions & 2 deletions packages/hooks/src/useImage/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ import {
ENV_TYPE,
} from '@tarojs/taro';
import { useCallback, useState } from 'react';
import Compressor from 'compressorjs';
import { useEnv } from '..';
import { saveImageForH5 } from './utils';
import { saveImageForH5, downloadImage, generateBlobUrl } from './utils';

export type ChooseImageOption = Partial<
Pick<chooseImage.Option, 'count' | 'sizeType' | 'sourceType'>
Expand Down Expand Up @@ -189,12 +190,24 @@ function useImage(options: IOptions): [IFileInfo, IAction] {

const compressImageAsync = useCallback<CompressImageAction>(
(src, quality) => {
return new Promise((resolve, reject) => {
return new Promise(async (resolve, reject) => {
if (!src) {
reject('you must provide src');
}
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,
});
} else {
compressImage({
src,
Expand Down
22 changes: 16 additions & 6 deletions packages/hooks/src/useImage/utils.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
export const downloadImage = async (filePath: string) => {
const responese = await fetch(filePath);
const blob = await responese.blob();
return blob;
};

export const generateBlobUrl = (blob: Blob): string => {
const blobInstance = new Blob([blob], {
type: 'application/octet-stream',
});
const href = window.URL.createObjectURL(blobInstance);
return href;
};

export const saveImageForH5 = async (filePath: string) => {
if (filePath) {
let result = true;
try {
const responese = await fetch(filePath);
const blob = await responese.blob();
const blobInstance = new Blob([blob], {
type: 'application/octet-stream',
});
const href = window.URL.createObjectURL(blobInstance);
const blob = await downloadImage(filePath);
const href = generateBlobUrl(blob);
const downloadElement = document.createElement('a');
downloadElement.href = href;
downloadElement.download = filePath.split('/').reverse()[0];
Expand Down

0 comments on commit 12fb4c4

Please sign in to comment.