Skip to main content

Autoconvert / autoresize image attachments

I wish T3 Chat would automatically resize or convert the clipboard contents format to a smaller png or jpg when the image is over the 4 MiB threshold so that I can just paste it directly and not get the “File too large” error.

Status: Completed2 comments

Log in to comment and vote

Comments2

  • Chocolate Pen

    const MAX_BYTES = 4 * 1024 * 1024;
    if (file.size > MAX_BYTES) {
      const compressedFile = await compressImage(file);
    }
    
    const compressImage = async (file: File): Promise<File> => {
      const img = await loadImage(file);
      const canvas = document.createElement('canvas');
      canvas.width = img.width;
      canvas.height = img.height;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0);
    
      let low = 0.1;
      let high = 1.0;
      let bestBlob: Blob | null = null;
      for (let i = 0; i < 10; i++) {
        const mid = (low + high) / 2;
        const blob = await blobFromCanvas(mid);
        if (blob.size <= MAX_BYTES) {
          bestBlob = blob;
          low = mid;
        } else {
          high = mid;
        }
      }
    
      const finalBlob = bestBlob || (await blobFromCanvas(low));
      const baseName = file.name.replace(/\.[^/.]+$/, '');
      const compressedFile = new File([finalBlob], `${baseName}.jpg`, { type: finalBlob.type });
    
      alert('Image was larger than 4 MB and has been ' + 'compressed to fit under the limit.');
      return compressedFile;
    };
    
    const blobFromCanvas = (quality: number): Promise<Blob> => {
      return new Promise((resolve, reject) => {
        canvas.toBlob(
          (blob) => {
            if (blob) resolve(blob);
            else reject(new Error('Blob creation failed'));
          },
          'image/jpeg',
          quality
        );
      });
    };
  • Chocolate Pen

    This would massively improve UX on mobile. Sometimes I want to take a picture of something and I get the 4 MB error. Meaning I would have to resize an image on my phone lol

    Here’s an example of a client-side function that could be used for this (made with the help of t3.chat :D ):