Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
export const compressImage = async (image, opts = {}) => {
// gif图片不压缩
if (image.type == "image/gif") {
return image;
}
let options = {
maxSizeMB: 0.8,
maxWidthOrHeight: 300,
useWebWorker: true,
maxIteration: 5,
...opts
};
try {
const compressedFile = await imageCompression(image, options);
console.log(
"compressedFile instanceof Blob",
compressedFile instanceof Blob
); // true
console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB
return compressedFile;
// await uploadToServer(compressedFile); // write your own logic
} catch (error) {
console.log(error);
}
};
export function uploadImage(img) {
handleOnFileDropAccepted = async ([file]) => {
// It's not an image
if (file.type.slice(0, 5) !== 'image')
return this.setState({
imageFileDataURL: null,
imageFileInfoMessage: 'File is not an image.'
})
// It's an image, try to compress it
let compressedFile =
file.type.slice(6, 9) === 'gif'
? file
: await browserImageCompression(file, 0.3)
// Sometimes compression can increase its size
compressedFile = file.size < compressedFile.size ? file : compressedFile
// It's still too big
if (compressedFile.size > 3e6)
return this.setState({
imageFileDataURL: null,
imageFileInfoMessage:
'Image is too big and cannot be resized. It must be less than 100KB.'
})
// It's small enough now, check dimensions
const imageFileDataURL = await browserImageCompression.getDataUrlFromFile(
compressedFile
)
const img = await browserImageCompression.loadImage(imageFileDataURL)
reader.onload = () => {
const arrayBuffer = reader.result
imageCompression(file, 0.1, 800)
.then(compressedFile => {
writeFile(photo.compressedPath, compressedFile, writeOptions)
photoProcessed()
})
.catch(() => {
displayError()
photoProcessed()
})
writeFile(photo.path, arrayBuffer, writeOptions)
.then(() => {
context.commit('prepend', photo)
photoProcessed()
})
.catch(() => {
displayError()
photoProcessed()
private compress(file: File) {
return imageCompression(file, {
maxSizeMB: 1,
maxWidthOrHeight: 600
});
}