PHP中的自动图像格式检测

MPX*_*MPX 21 php format jpeg image

我正在寻找一种方法来获取用户上传的图像,该图像当前放在临时位置ex:/ tmp/jkhjkh78并从中创建一个php图像,自动检测格式.

有没有比使用imagefromjpeg,imagefrompng等尝试/捕捉更聪明的方法呢?

Nea*_*all 27

这是getimagesize的功能之一.他们可能应该称之为"getimageinfo",但这对你来说就是PHP.


小智 5

exif_imagetype()如果可用则使用..:

http://www.php.net/manual/en/function.exif-imagetype.php

我很确定当您安装 php 时 exif 函数默认可用(即您必须专门排除它们而不是专门包含它们)


小智 5

   //Image Processing
    $cover = $_FILES['cover']['name'];
    $cover_tmp_name = $_FILES['cover']['tmp_name'];
    $cover_img_path = '/images/';
    $type = exif_imagetype($cover_tmp_name);

if ($type == (IMAGETYPE_PNG || IMAGETYPE_JPEG || IMAGETYPE_GIF || IMAGETYPE_BMP)) {
        $cover_pre_name = md5($cover);  //Just to make a image name random and cool :D
/**
 * @description : possible exif_imagetype() return values in $type
 * 1 - gif image
 * 2 - jpg image
 * 3 - png image
 * 6 - bmp image
 */
        switch ($type) {    #There are more type you can choose. Take a look in php manual -> http://www.php.net/manual/en/function.exif-imagetype.php
            case '1' :
                $cover_format = 'gif';
                break;
            case '2' :
                $cover_format = 'jpg';
                break;
            case '3' :
                $cover_format = 'png';
                break;
            case '6' :
                $cover_format = 'bmp';
                break;

            default :
                die('There is an error processing the image -> please try again with a new image');
                break;
        }
    $cover_name = $cover_pre_name . '.' . $cover_format;
      //Checks whether the uploaded file exist or not
            if (file_exists($cover_img_path . $cover_name)) {
                $extra = 1;
                while (file_exists($cover_img_path . $cover_name)) {
        $cover_name = md5($cover) . $extra . '.' . $cover_format;
                    $extra++;
                }
            }
     //Image Processing Ends
Run Code Online (Sandbox Code Playgroud)

这将使图像名称看起来很酷而且独特


ken*_*der 0

file如果您愿意,您可以调用系统命令(如果您在 linux/unix 下) :

kender@eira:~$ file a
a: JPEG image data, EXIF standard 2.2
Run Code Online (Sandbox Code Playgroud)