PHP/GD - 查找图像资源类型

标签 php image image-processing resources gd

只有有效的GD图片资源,是否可以查出原始图片的类型?

例如:

$image = ImageCreateFromPNG('http://sstatic.net/so/img/logo.png');

我能否获得只有 $image 变量可用的原始图像类型 (PNG)?

最佳答案

我不确定它是否可以从 $image 变量中完成,但要获取 MimeType,您通常可以使用以下四种中的任何一种:

// with GD
$img = getimagesize($path);
return $img['mime'];

// with FileInfo
$fi = new finfo(FILEINFO_MIME);
return $fi->file($path);

// with Exif (returns image constant value)
return exif_imagetype($path)

// deprecated
return mime_content_type($path);

根据你的问题描述,我认为你想使用远程文件,所以你可以做这样的事情来完成这项工作:

$tmpfname = tempnam("/tmp", "IMG_"); // use any path writable for you
$imageCopy = file_get_contents('http://www.example.com/image.png');
file_put_contents($tmpfname, $imageCopy);
$mimetype = // call any of the above functions on $tmpfname;
unlink($tmpfname);

注意:如果您要使用的 MimeType 函数支持远程文件,请直接使用它,而不是先创建文件的副本

如果您需要 MimeType 只是为了确定要使用哪个 imagecreatefrom 函数,为什么不先将文件作为字符串加载然后让 GD 决定,例如

// returns GD image resource of false
$imageString = file_get_contents('http://www.example.com/image.png');
if($imageString !== FALSE) {
    $image = imagecreatefromstring($imageString);
}

关于PHP/GD - 查找图像资源类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1965689/

相关文章:

php - pg_query_params 为 postgresql 提供日期参数

php - 如何在 php 中创建带有嵌套对象的响应 json?

python - 使用 opencv stitcher 模块拼接模糊图像

php - Composer 安装 * file_put_contents * 无法打开流

php - 错误处理请求 : Error in file: - SQLSTATE[42S01]: Base table or view already exists:

css - 使用 Nokogiri 保存图像

css - 使用 css 注入(inject)器的 drupal home 的大图像

javascript - 找不到图像源 CSS/HTML 的链接

visual-studio-2010 - 阅读隔行PNG时如何解决libpng警告?

image - 如何去除图像Python中的水印背景