XLR

megidochan jpeg paste

XLR
Sep 15th, 2020
1,640
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // convert pasted images to jpeg before posting
  2. document.body.addEventListener('paste', (e) => {
  3.     if (e.target.closest('[name=post]')) {
  4.         for (let i = 0; i < e.clipboardData.files.length; i++) {
  5.             const file = e.clipboardData.files[i];
  6.             if (file.type.startsWith('image')) {
  7.                 // create the canvas
  8.                 const canvas = document.createElement('canvas');
  9.                 const context = canvas.getContext('2d')
  10.                 // prepare the image in order to draw it on the canvas
  11.                 createImageBitmap(file).then((bmp) => {
  12.                   canvas.width = bmp.width;
  13.                   canvas.height = bmp.height;
  14.                   context.drawImage(bmp, 0, 0);
  15.                   // add the new canvas to what we're sending to the server
  16.                   canvas.toBlob((blob) => {
  17.                     // this doesn't play nicely with the multiple image upload js -- it'll overwrite the first image every time. ideally the addFile function it uses would be available, but that's ok
  18.                     $(document).on('ajax_before_post', (e, formData) => formData.append('file', blob, 'blob.jpg'))
  19.                   }, 'image/jpeg')
  20.                 })
  21.                 return false;
  22.             }
  23.         }
  24.     }
  25. });
RAW Paste Data