查找图像MIME类型

时间:2014-04-27 21:21:47

标签: php mime-types

在将图像保存到数据库之前,我没有运气获取上传图像的MIME类型。我读过书籍和几十个网页但找不到答案。

如何确定MIME类型?

这是我目前的代码。我删除了确定MIME类型的各种尝试:

$upload_dir = HOST_WWW_ROOT . "uploads/movie_pics/";
$image_fieldname = "movie_pic";

// Name the file uniquely
$now = time();
while (file_exists($upload_filename = $upload_dir . $now .
                                 '-' .
                                 $_FILES[$image_fieldname]['name'])) {
$now++;
}

// Insert the image into the movies_images table
$image = $_FILES[$image_fieldname];
$movie_images_filename = $image['name'];
$movie_images_info = getimagesize($image['tmp_name']);

$finfo = finfo_open();
$movie_images_mime_type = finfo_file($finfo, $upload_filename, FILEINFO_MIME);
finfo_close($finfo);


$movie_images_size = $image['size'];
$movie_images_data = file_get_contents($image['tmp_name']);

$insert_image_sql = sprintf("INSERT INTO movies_images " .
            "(movie_images_filename, movie_images_mime_type, movie_images_file_size,  movie_images_data) " .
                        "VALUES ('%s', '%s', %d, '%s');",
                        mysql_real_escape_string($movie_images_filename),
                        mysql_real_escape_string($movie_images_mime_type),
                        mysql_real_escape_string($movie_images_size),
                        mysql_real_escape_string($movie_images_data));

mysql_query($insert_image_sql)

或死(mysql_error());

2 个答案:

答案 0 :(得分:0)

如果您确定只会处理图片,可以使用exif_imagetype()

以下代码会将文件与特定的IMAGE类型进行比较。然后使用image_type_to_mime_type()使用$ image_type中存储的图像类型检索文件的mime类型。

示例1(从上面的链接中提取)

// if file is a GIF line below should return IMAGETYPE_GIF
$image_type = exif_imagetype('image.gif'); 

if ($image_type == IMAGETYPE_GIF) {
    $mime = image_type_to_mime_type(); // will produce "image/gif" as String.
    echo 'The picture is a gif, with a mime type of ' . $mime;
}

不要将mysql_ *用于新代码。

此外,建议不再对新代码使用 mysql _ * 函数,因为它已被弃用。我建议调查MySQL查询的mysqli_*PDO形式。

答案 1 :(得分:0)

finfo_file的手册页中,该示例将const FILEINFO_MIME_TYPE传递给finfo_open,而不是finfo_file。

$finfo = finfo_open(FILEINFO_MIME);
$movie_images_mime_type = finfo_file($finfo, $upload_filename);