LuanEdCosta / copy-image-clipboard

Lightweight library to copy PNG and JPG images to clipboard
https://luanedcosta.github.io/copy-image-clipboard/
MIT License
59 stars 12 forks source link

Options argument for the image copy #54

Open ashishk1331 opened 1 year ago

ashishk1331 commented 1 year ago

Is your feature request related to a problem? Please describe. [For SVGs only] I suggest providing an optional payload to the copyImageToClipboard and copyBlobToClipboard to overcome size-related issues and make it independent from the in-DOM size of images. Reference image: image Specifically, optional attributes to be used in place of the provided image's.

/**
 * Gets a blob from an image element.
 *
 * @param {HTMLImageElement} imageElement An image element
 * @returns {Promise<Blob>} A Promise that resolves to a image blob. Rejects the promise if cannot get a blob from the image element.
 */
function getBlobFromImageElement(imageElement) {
    return __awaiter(this, void 0, void 0, function* () {
        return new Promise(function (resolve, reject) {
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            if (context) {
                const { width, height } = imageElement;
                canvas.width = width;
                canvas.height = height;
                context.drawImage(imageElement, 0, 0, width, height);
                canvas.toBlob(function (blob) {
                    if (blob)
                        resolve(blob);
                    else
                        reject('Cannot get blob from image element');
                }, 'image/png', 1);
            }
        });
    });
}

Describe the solution you'd like

Instead, we can pass an optional parameter into the function as a payload and match the width and height attribute from it. Example:

function getBlobFromImageElement(imageElement, payload) {
    ...
    let width, height;
    if(payload){
       width  = payload.width;
       height = payload.height;
    } else {
        width  = imageElement.width;
        height = imageElement.height;
    }
    canvas.width = width;
    canvas.height = height;
    ...
}

Describe alternatives you've considered

A clear and concise description of any alternative solutions or features you've considered.

Additional context

  1. Apply this only for SVGs.
  2. Preserve image quality even for PNG and JPG.