Image processing src'时图像大小为零;d作为blob url,但在src';d作为数据url
我有一个图像blob,我想要它的高度和宽度,所以我创建了一个blob url,将图像对象的src设置为它,然后获得图像对象的高度和宽度Image processing src'时图像大小为零;d作为blob url,但在src';d作为数据url,image-processing,blob,clojurescript,Image Processing,Blob,Clojurescript,我有一个图像blob,我想要它的高度和宽度,所以我创建了一个blob url,将图像对象的src设置为它,然后获得图像对象的高度和宽度 (let [window-url (or (-> js/window .-URL) (-> js/window .-webkitURL)) blob-url (window-url.createObjectURL blob) image (js/Image.)] (
(let [window-url (or (-> js/window .-URL)
(-> js/window .-webkitURL))
blob-url (window-url.createObjectURL blob)
image (js/Image.)]
(set! (.-src image) blob-url)
(prn "image height" (.-height image))
(prn "image width " (.-width image))
)
但我得到的结果是:
图像高度0
图像宽度0
但很明显,图像的高度和宽度都不是0,我已经通过数据url在文档上显示了图像(然后我将其转换为上面提到的blob,如
(js/blob.[data url])
)验证了这一点。那么,如果文档上显示了相应的数据url,为什么blob的高度和宽度为零?请尝试显示图像的属性naturalWidth
和naturalHeight
:尝试显示图像的属性naturalWidth
和naturalHeight
:我很漂亮确保只有在图像“加载”后才能获得高度/宽度
,因此需要附加onload
事件处理程序。使用blob URL不会改变该限制
可能是这样的,不过我没有测试
(让[window url(或(->js/window.-url)
(->js/window.-webkitURL))
blob url(.createObjectURL窗口url blob)
图像(js/image.)]
(设置!(.-加载图像)
(fn[e]
(prn“图像高度”(.-高度图像))
(prn“图像宽度”(.-图像宽度)))
(设置!(-src image)blob url)
我非常确定,只有在图像“加载”后,才能获得高度/宽度,因此需要附加onload
事件处理程序。使用blob URL不会改变该限制
可能是这样的,不过我没有测试
(让[window url(或(->js/window.-url)
(->js/window.-webkitURL))
blob url(.createObjectURL窗口url blob)
图像(js/image.)]
(设置!(.-加载图像)
(fn[e]
(prn“图像高度”(.-高度图像))
(prn“图像宽度”(.-图像宽度)))
(设置!(-src image)blob url)
以下是我们在代码库中的实现方式。正如Thomas Heller指出的,您需要加载图像以获得适当的图像元数据
(defn with-image-data
"Asynchronously load an image `file` in a FileReader, then call the `callback`
fn with a proper Image object"
[file callback]
(let [reader (js/FileReader.)
img (js/Image.)]
(set! (.-onload reader) #(set! (.-src img) (.-result reader)))
(set! (.-onerror reader) #(js/console.error %))
(set! (.-onload img) (fn [_] (callback img)))
(.readAsDataURL reader file)
nil))
下面是我们在代码库中的实现方式。正如Thomas Heller指出的,您需要加载图像以获得适当的图像元数据
(defn with-image-data
"Asynchronously load an image `file` in a FileReader, then call the `callback`
fn with a proper Image object"
[file callback]
(let [reader (js/FileReader.)
img (js/Image.)]
(set! (.-onload reader) #(set! (.-src img) (.-result reader)))
(set! (.-onerror reader) #(js/console.error %))
(set! (.-onload img) (fn [_] (callback img)))
(.readAsDataURL reader file)
nil))
在onload函数中放入print语句时,不会打印任何内容。为什么会这样?\n当我将print语句放入onload函数中时,不会打印任何内容。为什么会这样?\n当我将print语句放入onload函数中时,不会打印任何内容。为什么会这样?可能无法加载?尝试添加一个onerror
事件处理程序,看看它是怎么说的。当我将print语句放入onload函数时,不会打印任何内容。为什么会这样?可能无法加载?尝试添加一个onerror
事件处理程序,看看会有什么结果。