GithubHelp home page GithubHelp logo

benwinding / quill-image-compress Goto Github PK

View Code? Open in Web Editor NEW
119.0 5.0 28.0 16.42 MB

A Quill rich text editor Module which compresses images uploaded to the editor

Home Page: https://benwinding.github.io/quill-image-compress/src/demo.html

License: MIT License

HTML 25.54% JavaScript 7.57% TypeScript 66.90%
quill compresses-images

quill-image-compress's Introduction

quill-image-compress

NPM Version License Downloads/week Github Issues Build and Publish

Quill.js Module which compresses images that are uploaded to the editor

Install

yarn add quill-image-compress

Features

  • Will compress image when:
    • Drag/Dropped into quill
    • Pasted into quill
    • Clicked image load button
  • Handles most image formats a browser can read:
    • gif|jpeg|png|svg|webp|bmp|vnd
  • Compression options more info
  • Add multiple images in one drag/paste

NOTE: ❗you don't need quill-image-drop-module, it's included in this package:exclamation:

Quickstart

import ImageCompress from 'quill-image-compress';

Quill.register('modules/imageCompress', ImageCompress);

const quill = new Quill(editor, {
  // ...
  modules: {
    // ...
    imageCompress: {
      quality: 0.7, // default
      maxWidth: 1000, // default
      maxHeight: 1000, // default
      imageType: 'image/jpeg', // default
      debug: true, // default
      suppressErrorLogging: false, // default
      handleOnPaste: true, //default 
      insertIntoEditor: undefined, // default
    }
  }
});

Quickstart (script tag)

    <script src="https://unpkg.com/[email protected]/dist/quill.imageCompressor.min.js"></script>
    <script>
      Quill.register("modules/imageCompressor", imageCompressor);
      
      var quill = new Quill("#editor", {
        modules: {
          imageCompressor: {
            quality: 0.9,
            maxWidth: 1000, // default
            maxHeight: 1000, // default
            imageType: 'image/jpeg'
          }
        }
      });
    </script>

Options

  • [Integer] maxWidth, maxHeight

    • Maximum width of images (in pixels)
  • [Float] quality

    • Image quality range: 0.0 - 1.0
  • [String] imageType

    • Values: 'image/jpeg' , 'image/png' ... etc
  • [Array] keepImageTypes
    Preserve image type and apply quality, maxWidth, maxHeight options

    • Values: ['image/jpeg', 'image/png']
  • [Array] ignoreImageTypes
    Image types contained in this array retain their original images, do not compress them.

    • Values: ['image'/jpeg', 'image/webp']
  • [Boolean] handleOnPaste

    • Compress image on paste, the default behaviour. Set to false to disable processing pasted images.
  • [Function] insertIntoEditor Custom function to handle inserting the image. If you wanted to upload the image to a webserver rather than embedding with Base64, you could use this function.

    • Example function, uploading to a webserver:
      insertIntoEditor: (imageBase64URL, imageBlob, editor) => {    
        const formData = new FormData();
        formData.append("file", imageBlob);
      
        fetch("/upload", {method: "POST", body: formData})
          .then(response => response.text())
          .then(result => {
            const range = editor.getSelection();
            editor.insertEmbed(range.index, "image", `${result}`, "user");
          })
          .catch(error => {
            console.error(error);
          });
      }
  • [Boolean] debug

    • Displays console logs: true/false

Thanks

This project is based on quill-image-uploader, thanks mate!

quill-image-compress's People

Contributors

benwinding avatar ckpuna4 avatar enzedonline avatar koenvg avatar leehanyeong avatar sercangurbuz avatar yenda avatar zeevl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

quill-image-compress's Issues

Problem saving content after image is compressed

Hey @benwinding .
First of all, thanks for the awesome initiative, I was really needing something like this.

I having a problem saving the context once the image is compressed. The image is compressed just fine on the editor, but once I save the data, the image (any image) is lost.

  1. Image resizes, but the content is lost during the saving process.
  2. The maxWidth property is working as the default width for any image.
  3. Everything was working just fine before the module quill-image-compress was added.
  4. I'm using the module on Angular.

component.ts

import ImageResize from 'quill-image-resize-module';
Quill.register('modules/imageResize', ImageResize);

import VideoResize from 'quill-video-resize-module';
Quill.register('modules/videoResize', VideoResize);

import ImageCompress from 'quill-image-compress';
Quill.register('modules/imageCompress', ImageCompress);

editorConfig = {
        toolbar: [
            ['bold', 'italic', 'underline'], // toggled buttons
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['link'],
            ['image', 'video']
        ],
        imageResize: {},
        videoResize: {},
        imageCompress: {
            quality: 1, // default
            maxWidth: 500, // default
            imageType: 'image/jpeg', // default
            debug: true, // default
        }
    };
    editorStyle = {
        height: '1000px'
    };

component.html

<quill-editor formControlName="description"
                                  placeholder="Enter Description text...."
                                  format="html"
                                  [styles]=editorStyle
                                  [modules]="editorConfig"

                                  (onContentChanged)="onEditorContentChange($event)"
                                  id="field_description">
                    </quill-editor>

Do you have any idea what's the problem?
Thank you for your time!

debug: false does not mute warn/error messages

Hi! I am using Quill with my custom toolbar and therefore default toolbar is not presented.

The module keeps spamming quill-image-compress: Quill toolbar module not found! which is true but everything works just fine for me.

Can I suggest adding if (!debug) check for error() and warn() as for log() method?

Editor loses focus when pasting

Hi Ben,

When pasting text or an image, editor loses focus and scrolls to the top.

Maybe saving cursor position before handling the clipboard contents and then resetting it could make the trick.

Best,
Roberto.

Dragging images inside of editor causes duplicate

Description:
When an image is dragged to a new position within the text, it is duplicated. This only occurs when this module is registered within the Quill editor.

This is easily reproducible through the demo provided in the README file.

Compresor bug animation

Steps to reproduce:

  1. Open the demo (script tag or normal).
  2. Add an image by any insertion method.
  3. Drag it to a new position.
  4. See that it is duplicated.

Environment:
Tested in the following environments on Windows 10:

  • Chrome 113.0.5672.127
  • Edge 113.0.1774.50
  • Firefox 113.0.2

Transparent images have a black background

When using the library using the script tag, if a PNG image with a transparent background is compressed into JPEG, the background becomes black instead of white
스크린샷 2021-12-06 오후 6 10 54
.

Below is the original image used.
absoluteholistic_dog_B103DF01_thumb02

Is it possible to compress gif format?

It seems like a gif file turning into a jpeg format. Can we compress gif format as well?

Putting 'image/gif' into ignoreImageTypes property doesn't help.

Security Concern: Remove Reference to Malicious polyfill.io Script

Hello,

I noticed that your project references cdn.polyfill.io in both demo.html and the README file. Recently, polyfill.io was reported as malicious, which poses a security risk.

Could you please provide an updated version of the package that removes any reference to this vulnerable script?

For more information, please refer to the following sources:

https://www.theregister.com/2024/06/25/polyfillio_china_crisis/
https://blog.cloudflare.com/polyfill-io-now-available-on-cdnjs-reduce-your-supply-chain-risk

vite build error

i try to build with vite
it show error log

➜  faceadmin git:(mr/master/richeditor) ✗ pnpm build

> [email protected] build /srv/project/faceadmin
> tsc && vite build

src/page/article.tsx:20:27 - error TS7016: Could not find a declaration file for module 'quill-image-compress'. '/srv/project/faceadmin/node_modules/.pnpm/[email protected]/node_modules/quill-image-compress/dist/quill.imageCompressor.min.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/quill-image-compress` if it exists or add a new declaration (.d.ts) file containing `declare module 'quill-image-compress';`

20 import ImageCompress from "quill-image-compress";
                             ~~~~~~~~~~~~~~~~~~~~~~


Found 1 error in src/page/article.tsx:20

version:

"quill-image-compress": "^1.2.26",

does quill-image-compress v1.2.26 support typescript?

Problem when including via script tag

Hi there,

I want to use the lib the classic way (similar to https://github.com/kensnyder/quill-image-drop-module#script-tag) and include it via the script tag like so (I took the minified file from the dist folder):

<script src="quill.imageCompressor.min.js"></script>

Then I want to register the module:

Quill.register('modules/imageCompress', ImageCompress);

But this command leeds to this JavaScript error: Uncaught ReferenceError: ImageCompress is not defined

I assume the min file is not indented to be used this way!? If so would it be possible to provide a file that could be used like I would like to use it?

addHandler error when used with quill-view

What happened
I have successfully integrated quill-image-compress by using Angular >= 9.
quill-editor is working as expected with the module.
When it is globally enabled, and you try to use quill-view, following error occured.

core.js:6228 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'addHandler' of undefined TypeError: Cannot read property 'addHandler' of undefined at new t (quill.imageCompressor.min.js:1) at SnowTheme.addModule (quill.js:6130) at SnowTheme.addModule (quill.js:6774) at quill.js:6122 at Array.forEach (<anonymous>) at SnowTheme.init (quill.js:6120) at new Quill (quill.js:1163) at ngx-quill.js:756 at ZoneDelegate.invoke (zone-evergreen.js:364) at Zone.run (zone-evergreen.js:123) at resolvePromise (zone-evergreen.js:798) at zone-evergreen.js:705 at fulfilled (tslib.es6.js:71) at ZoneDelegate.invoke (zone-evergreen.js:364) at Object.onInvoke (core.js:41654) at ZoneDelegate.invoke (zone-evergreen.js:363) at Zone.run (zone-evergreen.js:123) at zone-evergreen.js:857 at ZoneDelegate.invokeTask (zone-evergreen.js:399) at Object.onInvokeTask (core.js:41632)

What to expect
No interference by this module when using quill-view

More details

  • There is no image in the content
  • ImageDrop and ImageResize modules are also enabled
  • No error if I only disable ImageCompress

Piece of Source

app.module.ts
import { QuillModule } from 'ngx-quill';
@NgModule({
declarations: [
...
],
imports: [
...,
QuillModule.forRoot({
theme: 'snow',
modules: {
imageResize: {
debug: false,
},
imageCompress: {
quality: 0.7,
maxWidth: 512,
maxHeight: 512,
imageType: 'image/jpeg',
debug: true,
},
imageDrop: true,
}
}),
],
providers: [
...
],
bootstrap: [AppComponent]
})
export class AppModule { }
`

app.component.ts
let Quill: any = QuillNamespace; Quill.register('modules/imageResize', ImageResize); Quill.register('modules/imageCompress', ImageCompress); Quill.register('modules/imageDrop', ImageDrop); Quill.register('modules/quillMobileView', mobileView.module);

angular.json
... "styles": [ "node_modules/bootstrap/dist/css/bootstrap.min.css", "node_modules/quill/dist/quill.core.css", "node_modules/quill/dist/quill.snow.css", "src/styles.css" ], "scripts": [ "node_modules/jquery/dist/jquery.min.js", "node_modules/popper.js/dist/umd/popper.min.js", "node_modules/bootstrap/dist/js/bootstrap.min.js", "node_modules/quill/dist/quill.min.js" ] ...

app.component.html
<quill-editor #editor formControlName="short"></quill-editor> <quill-view [content]="data.short"></quill-view>

If you comment only ImageCompress, it is working without errors.

Failing to upload image file to server using the insertIntoEditor function. Getting empty file extension

I am trying to use quill-image-compress to compress my images before uploading them to server using the provided sample insertIntoEditor code below. The imageBlob is providing (1)image size and (2) image type but formData seem empty. My backend(Django) says the file extension is empty.

below is sample code from documentation(which is pretty much what I am using except I am using axios for fetching, but even if I use as it is the formaData is still the same):

insertIntoEditor: (imageBase64URL, imageBlob, editor) => {
const formData = new FormData();
formData.append("file", imageBlob);

fetch("/upload", {method: "POST", body: formData})
.then(response => response.text())
.then(result => {
const range = editor.getSelection();
editor.insertEmbed(range.index, "image", ${result}, "user");
})
.catch(error => {
console.error(error);
});
}

This is the result from a console log of the returned blob values:

Blob {size: 120193, type: 'image/jpeg'}
size: 120193
type: "image/jpeg"
[[Prototype]]: Blob

Pasted images aren't being compressed

Hey, love the package, it's been really useful in a project i'm currently working on.

I've been having an issue with inconsistent compressing while pasting images, i'm not too sure of how it works even after testing it for a while.
From what i've gathered, the image is only being compressed on paste if it also needs resizing.

Eg.: Using a quality of 0.1 (for exaggeration) with 1k x 1k size limit
If an image of 999 x 999 is pasted, it will keep it's original size and quality
If an image of 1001 x 1001 is pasted, it will be resized down and be compressed

It only seems to affect paste and not the other insertion methods.

image for context:
image

Even if this can't be helped, the package is already a BIG BIG help, so thanks anyways!

Incompatibility w/ React

.I cannot make this work with ReactQuill. Does this work with React package?

Sorry, I figured I need to import Quill from ReactQuill to make this work so there is no issue

Not working with Angular

import ImageCompress from 'quill-image-compress';

Quill.register('modules/imageCompress', ImageCompress);

const config: QuillConfig = {
  format: 'object',
  placeholder: QUILL_PLACEHOLDER,
  modules: {
    imageCompress: {
      quality: 0.5, // default
      maxWidth: 400, // default
      maxHeight: 400, // default
      debug: true, // default
    }
  }
}

@NgModule({
  imports: [
    QuillModule.forRoot(config)
  ]
})

This does nothing, no errors, no warning, no console.log()

Can you please show a angular working demo? how to make it work with Angular?

"@angular-devkit/build-angular": "~13.2.5",
"@angular/cli": "~13.2.5",
"@angular/compiler-cli": "~13.2.5",

Drag and Drop Support

It'd be great to see some sort of support for GIFs, whether that's via compressing them, or just taking the first frame of a GIF and inserting that instead of the whole GIF. Thanks so much for your work!

EDIT: Turns out it's an issue of drag and drop not utilizing this module, not that GIFs aren't supported. My mistake! Any change we could get drag and drop support? Thank you again!

Not compressing pasted images

When pasting an image straight into the editor, images are not compressed.

Would be great to include this use case.

Thank you.

no types

There are no ts types for this library.

Issue with Double Image Display in Quill Editor After Pasting

Environment: Next.js 14.2.4, quill-image-compress 1.2.33, Quill 2.0.2

Description:
After pasting an image into the editor, I expect to see only the processed image; however, the editor displays both the original and the processed images.

Console Output:

  • quill-image-compress: handleDataTransferList {fileTypes: Array(2), imageCount: 1}
  • quill.imageCompressor.min.js:1 quill-image-compress: pasteFilesIntoQuill pasting 1 images...
  • quill.imageCompressor.min.js:1 quill-image-compress: pasteFilesIntoQuill pasting image (0)
  • quill.imageCompressor.min.js:1 quill-image-compress: onImageDrop {dataUrl: 'data:image/png;base64,...
  • quill.imageCompressor.min.js:1 quill-image-compress: pasteFilesIntoQuill done
  • quill.imageCompressor.min.js:1 quill-image-compress: downscaling image... {args: {...}, newHeight: 4...
  • quill.imageCompressor.min.js:1 quill-image-compress: downscaleImageFromUrl {dataUrl: 'data:image/png;ba...
  • quill.imageCompressor.min.js:1 quill-image-compress: insertToEditor {url: 'data:image/png;base64,...'}
  • quill.imageCompressor.min.js:1 quill-image-compress: estimated img size: 480 kb

When using the toolbar to upload images, the feature works as expected, displaying only one processed image.

Thank you for your assistance.

console error: Logger is not defined

Hey! @benwinding @LeeHanYeong @koenvg
i am using quill-image-compress version 1.2.15 with react-quill its working fine, But when i upgarded quill-image-compress to version 1.2.23 my whole application is breaking and its giving error on console "Logger is not defined"

Screenshot from 2022-05-19 16-32-06

here the screen shot of error

I also checked in node_modules in version 1.2.15 there's file in node_modules/quill-image-compress folder called quill-imagecompress.js but in version 1.2.23 there no such file

i also have an error in my import line
Screenshot from 2022-05-19 16-40-34
Here the screen shot for that

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.