mirror of
https://github.com/stashapp/stash.git
synced 2025-12-17 20:34:37 +03:00
Encode pasted images to jpegs (#560)
This commit is contained in:
@@ -1,14 +1,15 @@
|
||||
import React, { useEffect } from "react";
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import Jimp from "jimp";
|
||||
|
||||
const readImage = (file: File, onLoadEnd: (this: FileReader) => void) => {
|
||||
const readImage = (file: File, onLoadEnd: (imageData: string) => void) => {
|
||||
const reader: FileReader = new FileReader();
|
||||
reader.onloadend = onLoadEnd;
|
||||
reader.onloadend = () => onLoadEnd(reader.result as string);
|
||||
reader.readAsDataURL(file);
|
||||
};
|
||||
|
||||
const pasteImage = (
|
||||
event: ClipboardEvent,
|
||||
onLoadEnd: (this: FileReader) => void
|
||||
onLoadEnd: (imageData: string) => void
|
||||
) => {
|
||||
const files = event?.clipboardData?.files;
|
||||
if (!files?.length) return;
|
||||
@@ -19,24 +20,41 @@ const pasteImage = (
|
||||
|
||||
const onImageChange = (
|
||||
event: React.FormEvent<HTMLInputElement>,
|
||||
onLoadEnd: (this: FileReader) => void
|
||||
onLoadEnd: (imageData: string) => void
|
||||
) => {
|
||||
const file = event?.currentTarget?.files?.[0];
|
||||
if (file) readImage(file, onLoadEnd);
|
||||
};
|
||||
|
||||
const usePasteImage = (
|
||||
onLoadEnd: (this: FileReader) => void,
|
||||
onLoadEnd: (imageData: string) => void,
|
||||
isActive: boolean = true
|
||||
) => {
|
||||
const [isEncoding, setIsEncoding] = useState(false);
|
||||
|
||||
const encodeImage = useCallback(
|
||||
(data: string) => {
|
||||
setIsEncoding(true);
|
||||
Jimp.read(data).then((image) =>
|
||||
image.quality(75).getBase64(Jimp.MIME_JPEG, (err, buffer) => {
|
||||
setIsEncoding(false);
|
||||
onLoadEnd(err ? "" : buffer);
|
||||
})
|
||||
);
|
||||
},
|
||||
[onLoadEnd]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const paste = (event: ClipboardEvent) => pasteImage(event, onLoadEnd);
|
||||
const paste = (event: ClipboardEvent) => pasteImage(event, encodeImage);
|
||||
if (isActive) {
|
||||
document.addEventListener("paste", paste);
|
||||
}
|
||||
|
||||
return () => document.removeEventListener("paste", paste);
|
||||
}, [isActive, onLoadEnd]);
|
||||
}, [isActive, encodeImage]);
|
||||
|
||||
return isEncoding;
|
||||
};
|
||||
|
||||
const Image = {
|
||||
|
||||
Reference in New Issue
Block a user