在php中获取远程图像的图像类型 [英] getting image type of remote image in php

查看:96
本文介绍了在php中获取远程图像的图像类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用预先构建的系统来抓取远程图像并将其保存到服务器。

Working on a prebuilt system that grabs remote images and saves them to a server.

目前还没有检查图像是否确实存在远程位置,它是一个特定的文件类型(jpg,jpeg,gif),我的任务是同时执行这两种操作。

Currently there is no checking on the image as to whether it indeed exists at that remote location, and it is of a certain file type (jpg, jpeg, gif) and I'm tasked with doing both.

我认为这对我来说非常微不足道只需使用简单的正则表达式和getimagesize($ image):

I thought this was quite trivial as I'd simply use a simple regex and getimagesize($image):

$remoteImageURL = 'http://www.exampledomain.com/images/image.jpg';

if(@getimagesize($remoteImageURL) && preg_match("/.(jpg|gif|jpeg)$/", $remoteImageURL) )
{
    // insert the image yadda yadda.
}

当我无法控制我的网址时出现问题例如,抓住图像:

The problem occurs when I don't have any control over the url that I'm grabbing the image from, for example:

http://www.exampledomain.com/images/2?num=1

因此,当涉及到这一点时,两者都是正则表达式和getimagesize()会失败,有没有更好的方法呢?

so when it comes to this, both the regex and getimagesize() will fail, is there a better way of doing this?

推荐答案

你可以做到

$headers = get_headers( 'http://www.exampledomain.com/images/2?num=1' );

$ headers 变量将包含一些内容喜欢

The $headers variable will then contain something like

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Date: Thu, 14 Oct 2010 09:46:18 GMT
    [2] => Server: Apache/2.2
    [3] => Last-Modified: Sat, 07 Feb 2009 16:31:04 GMT
    [4] => ETag: "340011c-3614-46256a9e66200"
    [5] => Accept-Ranges: bytes
    [6] => Content-Length: 13844
    [7] => Vary: User-Agent
    [8] => Expires: Thu, 15 Apr 2020 20:00:00 GMT
    [9] => Connection: close
    [10] => Content-Type: image/png
)

这将告诉您资源是否存在以及它是什么内容类型(不一定也是图像类型)。

This will tell you whether the resource exists and what content-type (which is not necessarily also the image type) it is.

编辑根据Pekka的评论,您仍然可能想要在下载后确定它的mime类型。见

EDIT as per Pekka's comment, you still might want to determine it's mime-type after downloading. See

  • How Can I Check If File Is MP3 Or Image File.

一些给定的方法也适用于远程文件,因此您可以完全跳过 get_headers 预先检查。确定哪一个适合您的需要。

Some of the given approaches work on remote files too, so you can probably skip the get_headers pre-check altogether. Decide for yourself which one suits your needs.

这篇关于在php中获取远程图像的图像类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆