javascript 从dataurl获取图像的高度和宽度

u5i3ibmn  于 2024-01-05  发布在  Java
关注(0)|答案(2)|浏览(173)

有一个图像作为dataurl的源代码,有没有一种方法可以在JavaScript或PHP中获得图像的高度和宽度,这样我就可以将它们设置为div的属性?
或者有没有更好的方法来使div缩放到图像大小。考虑一下图像在div的CSS中用作background-image属性。

krcsximq

krcsximq1#

如果你知道图像的长宽比,那么你可以创建一个响应式的<div>,它在页面调整大小时“模仿”原生的<img>元素。
例如,如果您有一个300 x180的图像,则纵横比为
1:0.6
(180/300=0.6)这意味着如果图像是100%宽,那么它是60%高。

  1. .image {
  2. background-image: url(http://lorempixel.com/output/nature-q-c-300-180-1.jpg);
  3. background-repeat: no-repeat;
  4. background-size: cover;
  5. padding-bottom: 60%;
  6. }

字符串
看到这个jsFiddle

46qrfjad

46qrfjad2#

我一直在解决同样的问题。我有代码可以工作,但不确定它是最佳的。这假设你是在浏览器上下文中运行。

  1. function onPhotoDrop(dropEvent) {
  2. dropEvent.preventDefault(); // don't let browser grab it
  3. const reader = new FileReader();
  4. reader.onloadend = function(eInner) {
  5. const dataURL = eInner.target.result;
  6. // Create a new img element and set its src attribute to the dropped image
  7. // We need to do this to obtain the photos size.
  8. const newImg = document.createElement("img");
  9. newImg.src = dataURL;
  10. newImg.onload = function() {
  11. // we need to wait till the image is loaded before proceeding.
  12. console.assert(newImg.width);
  13. console.assert(newImg.height);
  14. // here you would make a call to a function with the DataURL, width and height.
  15. }
  16. };
  17. reader.readAsDataURL(dropEvent.dataTransfer.files[0]);
  18. }

字符串
然后,您可以将其传递到一个合理的存储大小,

  1. function resizeImageSrc(
  2. elImg, // img.src must be set.
  3. minWidth,
  4. maxWidth,
  5. minHeight,
  6. maxHeight) {
  7. console.assert(minWidth <= maxWidth);
  8. console.assert(minHeight <= maxHeight);
  9. console.assert(elImg.tagName.toLowerCase() == 'img');
  10. console.assert(elImg.src);
  11. console.assert(elImg.width);
  12. console.assert(elImg.height);
  13. let wScale = 1;
  14. if (elImg.width > maxWidth) {
  15. wScale = maxWidth / elImg.width;
  16. } else if (elImg.width < minWidth){
  17. wScale = minWidth / elImg.width;
  18. }
  19. let hScale = 1;
  20. if (elImg.height > maxHeight) {
  21. hScale = maxHeight / elImg.height;
  22. } else if (elImg.height < minHeight){
  23. hScale = minHeight / elImg.height;
  24. }
  25. // shrink or grow to fit - favor the smaller scale
  26. let scale = hScale < wScale ? hScale : wScale;
  27. const canvas = document.createElement("canvas");
  28. canvas.width = Math.floor(elImg.width * scale);
  29. canvas.height = Math.floor(elImg.height * scale);
  30. canvas.getContext("2d").drawImage(elImg, 0, 0, canvas.width, canvas.height);
  31. elImg.src = canvas.toDataURL();
  32. // or just return canvas.toDataURL(); if that's what you want.
  33. }

展开查看全部

相关问题