fix: adjust image size when paste

This commit is contained in:
jialin
2024-10-17 13:32:38 +08:00
parent a47f7cc0ce
commit 349676d908
6 changed files with 85 additions and 57 deletions
+34
View File
@@ -0,0 +1,34 @@
import { Image as AntImage, ImageProps } from 'antd';
import { round } from 'lodash';
import React, { useCallback, useEffect, useState } from 'react';
const AutoImage: React.FC<ImageProps & { height: number }> = (props) => {
const { height = 100, ...rest } = props;
const [width, setWidth] = useState(0);
const getImgRatio = useCallback((url: string): Promise<{ ratio: number }> => {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
resolve({ ratio: round(img.width / img.height, 2) });
};
img.onerror = () => {
resolve({ ratio: 1 });
};
img.src = url;
});
}, []);
const handleOnLoad = useCallback(async () => {
const { ratio } = await getImgRatio(props.src || '');
setWidth(height * ratio);
}, [getImgRatio, height, props.src]);
useEffect(() => {
handleOnLoad();
}, [handleOnLoad]);
return <AntImage {...rest} height={height} width={width} />;
};
export default AutoImage;