簡體   English   中英

如何顯示用戶上傳的圖片的原始尺寸?

[英]How to display the original size of an image that was uploaded by a user?

我正在通過從頭開始創建個人項目來學習 web 開發。 基本上我想設計一個類似於 9GAG(用戶生成的內容網站)的網站。 我在顯示上傳的圖像的過程中遇到了困難。 圖像會顯示,但它會適應 div 元素的尺寸。 我想要相反的: div 適應圖像的原始尺寸。 I read that I should code some PHP that would get the image dimensions ( getImageSize() ) and then write JavaScript that would change the div's width and height based on the result from the PHP function. 我真的不知道這兩個會如何相互影響。

那么,您有什么適合我需要的建議或解決方案嗎?

謝謝你,馬可

一般來說,這是一個非常糟糕的主意,因為這樣人們就可以上傳大量圖片,這會破壞網頁。

您的網站應該有一個最大寬度:

.wrapper {
  max-width: 1200px;
  margin: 0 auto;
}

您的圖像還應該:

.image {
  max-width: 80%;
  height: auto;
  margin: 0 auto;
}

這樣它就不會破壞屏幕尺寸。 如果您絕對必須將其設為全尺寸,即使其寬度為 20,000 像素,則將其設為在新選項卡中單擊target="_blank"的新鏈接。

<a href="file.png" target="_blank"><img src="file.png"></a>

至於PHP端,有很多關於如何通過PHP上傳文件的指南。 要考慮的主要問題是安全性,因為人們可以在上傳內容中嵌入討厭的程序,因此請確保您使用的示例具有一定的安全性(限制文件擴展名和 mime 類型等)

像這樣: https://stackoverflow.com/a/52663580/794481

在 PHP 中,您可以使用 getimagesize() function 獲取有關上傳圖像的詳細信息

例子:

// Calling getimagesize() function 
list($width, $height, $type, $attr) = getimagesize("image.png"); 

// Displaying dimensions of the image 
echo "Width of image : " . $width . "<br>"; 

echo "Height of image : " . $height . "<br>"; 

echo "Image type :" . $type . "<br>"; 

echo "Image attribute :" .$attr; 

至於實際以上傳大小顯示圖像,我還不得不說這樣做是一個壞主意,因為您的整個布局可能會中斷,但也許應該做的是創建一個合適大小的縮略圖並使用燈箱單擊時以正常大小顯示圖像。

您可以使用naturalWidthnaturalHeight屬性。 不需要 PHP。

 document.querySelector(`img`).addEventListener(`load`, function(){ console.log(`width: ${this.naturalWidth}`); console.log(`height: ${this.naturalHeight}`); });
 img { width: 100px; height: 100px; }
 <img src="http://pluspng.com/img-png/logo-javascript-png-file-javascript-logo-png-1052.png">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM