簡體   English   中英

在PHP中使用ImageCreateFromString和getimagesize

[英]ImageCreateFromString and getimagesize in PHP

目前,如果用戶POST /上傳照片到我的PHP腳本,我開始使用這樣的代碼

getimagesize($_FILES['picture1']['tmp_name']);

然后我做了很多其他的東西,但我也試圖從URL獲取一張照片並用我的其他現有代碼處理它,如果可以的話。 所以我想知道,我使用這樣的東西

$image = ImageCreateFromString(file_get_contents($url));

我能在我的$ image變量上運行getimagesize()嗎?



UPDATE

我剛試過這個......

$url = 'http://a0.twimg.com/a/1262802780/images/twitter_logo_header.png';
$image = imagecreatefromstring(file_get_contents($url));
$imageinfo = getimagesize($image);
print_r($imageinfo);

但它沒有用,給了這個。

Warning: getimagesize(Resource id #4) [function.getimagesize]: failed to open stream: No such file or directory in

知道如何做到這一點或類似的東西,以獲得我追求的結果?

我建議你按照這種方法:

// if you need the image type
$type = exif_imagetype($url);

// if you need the image mime type
$type = image_type_to_mime_type(exif_imagetype($url));

// if you need the image extension associated with the mime type
$type = image_type_to_extension(exif_imagetype($url));

// if you don't care about the image type ignore all the above code
$image = ImageCreateFromString(file_get_contents($url));

echo ImageSX($image); // width
echo ImageSY($image); // height

使用exif_imagetype()getimagesize()快得多, ImageSX() / ImageSY() ,加上它們不返回數組, 並且在調整圖像大小或裁剪后也可以返回正確的圖像尺寸。

此外,在URL上使用getimagesize()並不好,因為它將比PHP手冊中的替代exif_imagetype()消耗更多的帶寬:

找到正確的簽名后,將返回相應的常量值,否則返回值為FALSE。 返回值與getimagesize()在索引2中返回的值相同,但exif_imagetype()更快。

那是因為exif_imagetype()只會讀取數據的前幾個字節。

如果您已經擁有圖像資源,則可以使用imagesx和imagesy函數獲得大小。

getimagesize可以與HTTP一起使用。

文件名 - 它可以使用其中一個支持的流引用本地文件或(配置允許) 遠程文件

從而

$info = getimagesize($url);
$image = ImageCreateFromString(file_get_contents($url));

應該沒事。

不確定這是否有幫助,但我遇到了類似的問題,結果發現我的主機控制的防火牆阻止了從我的服務器傳出的http連接。

他們更改了防火牆設置。 然后我的代碼工作了。

順便說一句:當我在許多網址上嘗試使用file_get_contents()時,我認為這可能是一個問題,但沒有一個工作!

暫無
暫無

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

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