-
米脂
创建一个将加载图像文件并返回尺寸的承诺const imageWidthAndHeight = (provideFile) => { // take the given file (which should be an image) and return the width and height const imgDimensions = { width: null, height: null }; return new Promise(resolve => { const reader = new FileReader(); reader.readAsDataURL(provideFile); reader.onload = function () { const img = new Image(); img.src = reader.result; img.onload = function () { imgDimensions.width = img.width; imgDimensions.height = img.height; resolve(imgDimensions); } }; });}在自定义 yup 函数中调用并等待 Promise(使用 addMethod),并添加额外的验证来检查宽度和高度。const imageDimensionCheck = Yup.addMethod(Yup.mixed, 'imageDimensionCheck', function (message, requiredWidth, requiredHeight) { return this.test("image-width-height-check", message, async function (value) { const { path, createError } = this; if (!value) { return; } const imgDimensions = await imageWidthAndHeight(value); if (imgDimensions.width !== requiredWidth) { return createError({ path, message: `The file width needs to be the ${requiredWidth}px!` }); } if (imgDimensions.height !== requiredHeight) { return createError({ path, message: `The file height needs to be the ${requiredHeight}px!` }); } return true; });});在formik中调用创建的Yup方法<Formik initialValues={{ bookCoverPhoto: null, }} validationSchema={ Yup.object().shape({ bookCoverPhoto: Yup.mixed() .required('You need to provide a file') .imageDimensionCheck('test', 1988, 3056) }) }>....Stuff</Formik>
-
冉冉说
这里有两种替代方法,它们比 Base64 编码(解码)更快,并且不需要文件读取器function checkAspectRatio (file) { const img = new Image() img.src = URL.createObjectURL(file) return img.decode().then(() => { URL.revokeObjectURL(img.src) return img.width / img.height })}// not as cross compatiblefunction checkAspectRatio (file) { return createImageBitmap(file) .then(bitmap => bitmap.width / bitmap.height)}
-
梦里花落0921
image: Yup.mixed() .required("Image is required.") .test( "aspectRatio", "Aspect ratio must be 16:9", value => { return new Promise(resolve => { const reader = new FileReader(); reader.readAsDataURL(value[0]); reader.onload = function(value) { const img = new Image(); img.src = value.target.result; img.onload = function() { const aspectRatio = this.width / this.height; resolve(aspectRatio === (16 / 9)); }; }; }); } ),
-
慕勒3428872
我设法使用这个功能来做到这一点function checkAspectRatio(value) { return new Promise(resolve => { const reader = new FileReader(); reader.readAsDataURL(value); reader.onload = function(value) { const img = new Image(); img.src = value.target.result; img.onload = function() { const aspectRatio = this.width / this.height; resolve(aspectRatio); }; }; });}用于Object.defineProperty()在对象上定义新属性Object.defineProperty(file, 'aspectRatio', { value: await checkAspectRatio(file)});并使用 yup 测试该值.test( 'fileAspectRatio', 'Please recheck the image resolution', value => value && value.aspectRatio === 1.6);