問題描述
我聽說處理上傳圖像的最佳方法是使用 GD
庫重新處理"它們并保存處理后的圖像.參見:PHP圖片上傳安全檢查清單
我的問題是如何在 GD
中進行這種重新處理"?這究竟是什么意思?我對GD庫不是很了解,怕把它搞砸了...
I've heard that the best way to handle uploaded images is to "re-process" them using the GD
library and save the processed image. see: PHP image upload security check list
My question is how do this "re-processing" in GD
? What this means exactly? I don't know the GD library very well and I'm afraid I will mess it up...
所以如果有人之前做過這件事,你能給我舉個例子嗎?
So if anyone who did this before could you give me an example for this?
(我知道,另一種選擇是使用 ImageMagick.對于 ImageMagick,我在這里找到了答案:使用 PHP 從 JPG 中刪除 EXIF 數據,但我現在不能使用 ImgMagick.順便說一句.. 在這種情況下,刪除 EXIF 數據意味著完全重新創建圖像?)
(如果有人感興趣,我正在使用 Zend 框架.)
(I know, another other option is to use ImageMagick. For ImageMagick I found an answer here: Remove EXIF data from JPG using PHP, but I can't use ImgMagick now. By the way.. removing EXIF data means completely recreate the image in this case?)
(I'm using Zend Framework if someone interested.)
推薦答案
如果用戶上傳了一個 JPEG 文件,你可以做這樣的事情來重新處理它:
If the user uploads a JPEG file, you could do something like this to reprocess it:
$newIm = @imagecreatefromjpeg($_FILES['file']['tmp_name']);
if (!$newIm) {
// gd could not create an image from the source
// most likely, the file was not a valid jpeg image
}
然后您可以使用 imagedestroy() 丟棄 $newIm
圖像并使用從用戶上傳的文件,或者從 GD 中保存圖像并使用它.保存 GD 圖像可能存在一些問題,因為它不是原始圖像.
You could then discard the $newIm
image using imagedestroy() and use the uploaded file from the user, or save out the image from GD and use that. There could be some issues with saving the GD image as it is not the original image.
另一種簡單的方法是檢查圖像文件的標題(前幾個字節)以確保其正確;例如,所有 JPEG 文件都以 0xff 0xd8
開頭.
Another simple method would be to check the header (first several bytes) of the image file to make sure it is correct; for example all JPEG files begin with 0xff 0xd8
.
另見imagecreatefromstring(),你也可以使用getimagesize() 對上傳的圖片運行類似的檢查.
See also imagecreatefromstring(), and you can also use getimagesize() to run similar checks on the uploaded image.
這篇關于圖片上傳安全 - 使用 GD 重新處理的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!