Browse Source

Merge branch 'main' into fix

pull/6997/head
xingyu 3 weeks ago
committed by GitHub
parent
commit
8571fc43b0
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 33
      apps/web-antd/src/adapter/component/index.ts
  2. 57
      packages/effects/common-ui/src/components/cropper/cropper.vue
  3. 1
      packages/locales/src/langs/en-US/ui.json
  4. 1
      packages/locales/src/langs/zh-CN/ui.json
  5. 33
      playground/src/adapter/component/index.ts
  6. 6
      playground/src/views/examples/cropper/index.vue

33
apps/web-antd/src/adapter/component/index.ts

@ -312,7 +312,16 @@ const withPreviewUpload = () => {
Modal, Modal,
{ {
open: open.value, open: open.value,
title: $t('ui.crop.title'), title: h('div', {}, [
$t('ui.crop.title'),
h(
'span',
{
class: `${aspectRatio ? '' : 'hidden'} ml-2 text-sm text-gray-400 font-normal`,
},
$t('ui.crop.titleTip', [aspectRatio]),
),
]),
centered: true, centered: true,
width: 548, width: 548,
keyboard: false, keyboard: false,
@ -357,22 +366,6 @@ const withPreviewUpload = () => {
}); });
}; };
const base64ToBlob = (base64: Base64URLString) => {
try {
const [typeStr, encodeStr] = base64.split(',');
if (!typeStr || !encodeStr) return;
const mime = typeStr.match(/:(.*?);/)?.[1];
const raw = window.atob(encodeStr);
const rawLength = raw.length;
const uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.codePointAt(i) as number;
}
return new Blob([uInt8Array], { type: mime });
} catch {
return undefined;
}
};
return defineComponent({ return defineComponent({
name: Upload.name, name: Upload.name,
emits: ['update:modelValue'], emits: ['update:modelValue'],
@ -408,12 +401,8 @@ const withPreviewUpload = () => {
) { ) {
file.status = 'removed'; file.status = 'removed';
// antd Upload组件问题 file参数获取的是UploadFile类型对象无法取到File类型 所以通过originFileList[0]获取 // antd Upload组件问题 file参数获取的是UploadFile类型对象无法取到File类型 所以通过originFileList[0]获取
const base64 = await cropImage(originFileList[0], attrs.aspectRatio); const blob = await cropImage(originFileList[0], attrs.aspectRatio);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!base64) {
return reject(new Error($t('ui.crop.cancel')));
}
const blob = base64ToBlob(base64 as string);
if (!blob) { if (!blob) {
return reject(new Error($t('ui.crop.errorTip'))); return reject(new Error($t('ui.crop.errorTip')));
} }

57
packages/effects/common-ui/src/components/cropper/cropper.vue

@ -523,20 +523,25 @@ const handleImageLoad = () => {
* 裁剪图片 * 裁剪图片
* @param {'image/jpeg' | 'image/png'} format - 输出图片格式 * @param {'image/jpeg' | 'image/png'} format - 输出图片格式
* @param {number} quality - 压缩质量0-1 * @param {number} quality - 压缩质量0-1
* @param {'blob' | 'base64'} outputType - 输出类型
* @param {number} targetWidth - 目标宽度可选不传则为原始裁剪宽度 * @param {number} targetWidth - 目标宽度可选不传则为原始裁剪宽度
* @param {number} targetHeight - 目标高度可选不传则为原始裁剪高度 * @param {number} targetHeight - 目标高度可选不传则为原始裁剪高度
*/ */
const getCropImage = async ( const getCropImage = async (
format: 'image/jpeg' | 'image/png' = 'image/jpeg', format: 'image/jpeg' | 'image/png' = 'image/jpeg',
quality: number = 0.92, quality: number = 0.92,
outputType: 'base64' | 'blob' = 'blob',
targetWidth?: number, targetWidth?: number,
targetHeight?: number, targetHeight?: number,
): Promise<string | undefined> => { ): Promise<Blob | string | undefined> => {
if (!props.img || !bgImageRef.value || !containerRef.value) return; if (!props.img || !bgImageRef.value || !containerRef.value) return;
// 0-1
const validQuality = Math.max(0, Math.min(1, quality));
// //
const tempImg = new Image(); const tempImg = new Image();
// Only set crossOrigin for cross-origin URLs that need CORS //
if (props.img.startsWith('http://') || props.img.startsWith('https://')) { if (props.img.startsWith('http://') || props.img.startsWith('https://')) {
try { try {
const url = new URL(props.img); const url = new URL(props.img);
@ -544,7 +549,7 @@ const getCropImage = async (
tempImg.crossOrigin = 'anonymous'; tempImg.crossOrigin = 'anonymous';
} }
} catch { } catch {
// Invalid URL, proceed without crossOrigin // Invalid URL
} }
} }
@ -553,7 +558,7 @@ const getCropImage = async (
const timeout = setTimeout(() => { const timeout = setTimeout(() => {
tempImg.removeEventListener('load', handleLoad); tempImg.removeEventListener('load', handleLoad);
tempImg.removeEventListener('error', handleError); tempImg.removeEventListener('error', handleError);
reject(new Error('图片加载超时')); reject(new Error('图片加载超时,超时时间10秒'));
}, 10_000); }, 10_000);
const handleLoad = () => { const handleLoad = () => {
clearTimeout(timeout); clearTimeout(timeout);
@ -571,7 +576,6 @@ const getCropImage = async (
tempImg.addEventListener('load', handleLoad); tempImg.addEventListener('load', handleLoad);
tempImg.addEventListener('error', handleError); tempImg.addEventListener('error', handleError);
tempImg.src = props.img; tempImg.src = props.img;
}); });
@ -595,11 +599,11 @@ const getCropImage = async (
const cropOnImgX = cropLeft - imgOffsetX; const cropOnImgX = cropLeft - imgOffsetX;
const cropOnImgY = cropTop - imgOffsetY; const cropOnImgY = cropTop - imgOffsetY;
// 4. // 4.
const scaleX = tempImg.width / renderedImgWidth; const scaleX = tempImg.width / renderedImgWidth;
const scaleY = tempImg.height / renderedImgHeight; const scaleY = tempImg.height / renderedImgHeight;
// 5. // 5.
const originalCropX = Math.max(0, Math.floor(cropOnImgX * scaleX)); const originalCropX = Math.max(0, Math.floor(cropOnImgX * scaleX));
const originalCropY = Math.max(0, Math.floor(cropOnImgY * scaleY)); const originalCropY = Math.max(0, Math.floor(cropOnImgY * scaleY));
const originalCropWidth = Math.min( const originalCropWidth = Math.min(
@ -611,27 +615,32 @@ const getCropImage = async (
tempImg.height - originalCropY, tempImg.height - originalCropY,
); );
// 6. Retina //
if (originalCropWidth <= 0 || originalCropHeight <= 0) return;
// 6. Retina
const dpr = window.devicePixelRatio || 1; const dpr = window.devicePixelRatio || 1;
// 使 // 使
const finalWidth = targetWidth || originalCropWidth; const finalWidth = targetWidth ? Math.max(1, targetWidth) : originalCropWidth;
const finalHeight = targetHeight || originalCropHeight; const finalHeight = targetHeight
? Math.max(1, targetHeight)
: originalCropHeight;
// //
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');
if (!ctx) return; if (!ctx) return;
// //
canvas.width = finalWidth * dpr; canvas.width = finalWidth * dpr;
canvas.height = finalHeight * dpr; canvas.height = finalHeight * dpr;
// //
canvas.style.width = `${finalWidth}px`; canvas.style.width = `${finalWidth}px`;
canvas.style.height = `${finalHeight}px`; canvas.style.height = `${finalHeight}px`;
// DPR // DPR
ctx.scale(dpr, dpr); ctx.scale(dpr, dpr);
// 7. 使 // 7. 使
@ -647,8 +656,22 @@ const getCropImage = async (
finalHeight, // finalHeight, //
); );
// 8. try {
return canvas.toDataURL(format, quality); return outputType === 'base64'
? canvas.toDataURL(format, validQuality)
: new Promise<Blob>((resolve) => {
canvas.toBlob(
(blob) => {
// blobBlobnull
resolve(blob || new Blob([], { type: format }));
},
format,
validQuality,
);
});
} catch (error) {
console.error('图片导出失败:', error);
}
}; };
// //

1
packages/locales/src/langs/en-US/ui.json

@ -56,6 +56,7 @@
}, },
"crop": { "crop": {
"title": "Image Cropping", "title": "Image Cropping",
"titleTip": "Cropping Ratio {0}",
"confirm": "Crop", "confirm": "Crop",
"cancel": "Cancel cropping", "cancel": "Cancel cropping",
"errorTip": "Cropping error" "errorTip": "Cropping error"

1
packages/locales/src/langs/zh-CN/ui.json

@ -56,6 +56,7 @@
}, },
"crop": { "crop": {
"title": "图片裁剪", "title": "图片裁剪",
"titleTip": "裁剪比例 {0}",
"confirm": "裁剪", "confirm": "裁剪",
"cancel": "取消裁剪", "cancel": "取消裁剪",
"errorTip": "裁剪错误" "errorTip": "裁剪错误"

33
playground/src/adapter/component/index.ts

@ -312,7 +312,16 @@ const withPreviewUpload = () => {
Modal, Modal,
{ {
open: open.value, open: open.value,
title: $t('ui.crop.title'), title: h('div', {}, [
$t('ui.crop.title'),
h(
'span',
{
class: `${aspectRatio ? '' : 'hidden'} ml-2 text-sm text-gray-400 font-normal`,
},
$t('ui.crop.titleTip', [aspectRatio]),
),
]),
centered: true, centered: true,
width: 548, width: 548,
keyboard: false, keyboard: false,
@ -357,22 +366,6 @@ const withPreviewUpload = () => {
}); });
}; };
const base64ToBlob = (base64: Base64URLString) => {
try {
const [typeStr, encodeStr] = base64.split(',');
if (!typeStr || !encodeStr) return;
const mime = typeStr.match(/:(.*?);/)?.[1];
const raw = window.atob(encodeStr);
const rawLength = raw.length;
const uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.codePointAt(i) as number;
}
return new Blob([uInt8Array], { type: mime });
} catch {
return undefined;
}
};
return defineComponent({ return defineComponent({
name: Upload.name, name: Upload.name,
emits: ['update:modelValue'], emits: ['update:modelValue'],
@ -408,12 +401,8 @@ const withPreviewUpload = () => {
) { ) {
file.status = 'removed'; file.status = 'removed';
// antd Upload组件问题 file参数获取的是UploadFile类型对象无法取到File类型 所以通过originFileList[0]获取 // antd Upload组件问题 file参数获取的是UploadFile类型对象无法取到File类型 所以通过originFileList[0]获取
const base64 = await cropImage(originFileList[0], attrs.aspectRatio); const blob = await cropImage(originFileList[0], attrs.aspectRatio);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!base64) {
return reject(new Error($t('ui.crop.cancel')));
}
const blob = base64ToBlob(base64 as string);
if (!blob) { if (!blob) {
return reject(new Error($t('ui.crop.errorTip'))); return reject(new Error($t('ui.crop.errorTip')));
} }

6
playground/src/views/examples/cropper/index.vue

@ -44,7 +44,11 @@ const cropImage = async () => {
if (!cropperRef.value) return; if (!cropperRef.value) return;
cropLoading.value = true; cropLoading.value = true;
try { try {
cropperImg.value = await cropperRef.value.getCropImage(); cropperImg.value = await cropperRef.value.getCropImage(
'image/jpeg',
0.92,
'base64',
);
} catch (error) { } catch (error) {
console.error('图片裁剪失败:', error); console.error('图片裁剪失败:', error);
} finally { } finally {

Loading…
Cancel
Save