Cloud Defense Logo

Products

Solutions

Company

Book A Live Demo

Top 8 Examples of "browser-image-compression in functional component" in JavaScript

Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'browser-image-compression' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.

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) {
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
            }
        }
    }
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)
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
    })
  }
// 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
    })
  }
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
        });
    }
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

Is your System Free of Underlying Vulnerabilities?
Find Out Now