How to use browser-image-compression - 8 common examples

To help you get started, we’ve selected a few browser-image-compression examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github zerosoul / static-site-data-management / frontend / src / utils.js View on Github external
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) {
github CharlBest / nean-stack-starter / src / client / app / shared / file-uploader / file-uploader / file-uploader.component.ts View on Github external
for (const file of Array.from(files)) {
            let error = '';

            // Max file size
            if ((file.size / 1024 / 1024 /*in MB*/) > this.maxFileSizeInMB) {
                error = `File exceeds ${this.maxFileSizeInMB} MB. Please upload a smaller file`;
                return;
            }

            try {
                const compressedFile = await this.compress(file);
                const metadata = await this.preview(compressedFile);

                // https://stackoverflow.com/a/32490603/10395024
                // https://i.stack.imgur.com/VGsAj.gif
                const exifOrientation = await imageCompression.getExifOrientation(file);

                this.previewImages.push({
                    file: compressedFile,
                    ...metadata,
                    exifOrientation,
                    errorMessage: error
                });

                this.changed.emit();
            } catch (error) {
                // TODO: error handling
            }
        }
    }
github kleros / doges-on-trial / src / containers / doge-modal / index.js View on Github external
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)
github kleros / doges-on-trial / src / containers / doge-modal / index.js View on Github external
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)
    if (img.width < 250 || img.height < 250)
      return this.setState({
        imageFileDataURL: null,
        imageFileInfoMessage:
          'Image is too small. It must be more than 250px wide and 250px tall.'
      })

    // All good
    this.setState({
      imageFileDataURL,
      imageFileInfoMessage: null
    })
  }
github kleros / doges-on-trial / src / containers / doge-modal / index.js View on Github external
// 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)
    if (img.width < 250 || img.height < 250)
      return this.setState({
        imageFileDataURL: null,
        imageFileInfoMessage:
          'Image is too small. It must be more than 250px wide and 250px tall.'
      })

    // All good
    this.setState({
      imageFileDataURL,
      imageFileInfoMessage: null
    })
  }
github recall-photos / recall-app / src / vuex / stores / photo_store.js View on Github external
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()
github CharlBest / nean-stack-starter / src / client / app / shared / file-uploader / file-uploader / file-uploader.component.ts View on Github external
private compress(file: File) {
        return imageCompression(file, {
            maxSizeMB: 1,
            maxWidthOrHeight: 600
        });
    }
github nerdic-coder / block-photos / src / services / photos-service.ts View on Github external
PhotoType.Thumbnail,
          metadata.type
        );
        await StorageService.setItem(mainId + '-thumbnail', thumbnailData);

        rawPhoto = thumbnailData;
      } else {
        photoType = PhotoType.Download;
      }
    } else if (!rawPhoto && photoType === PhotoType.Viewer) {
      rawPhoto = await StorageService.getItem(mainId, false);
      const { Device } = Plugins;
      const info = await Device.getInfo();
      if (info.model !== 'iPhone' && info.model !== 'iPad') {
        const viewerData = await PhotosService.compressPhoto(
          await imageCompression.getFilefromDataUrl(rawPhoto),
          PhotoType.Viewer,
          metadata.type
        );
        await StorageService.setItem(mainId + '-viewer', viewerData, true);
        rawPhoto = viewerData;
      } else {
        photoType = PhotoType.Download;
      }
    }

    if (!rawPhoto) {
      return false;
    }

    if (rawPhoto && !rawPhoto.match('data:image/.*')) {
      metadata.type