Create Image From Url Any File Type
Maybe you want this:
$jpeg_image = imagecreatefromfile( 'photo.jpeg' );
$gif_image = imagecreatefromfile( 'clipart.gif' );
$png_image = imagecreatefromfile( 'transparent_checkerboard.PnG' );
$another_jpeg = imagecreatefromfile( 'picture.JPG' );
// This requires you to remove or rewrite file_exists check:
$jpeg_image = imagecreatefromfile( 'http://example.net/photo.jpeg' );
// SEE BELOW HO TO DO IT WHEN http:// ARGS IS NEEDED:
$jpeg_image = imagecreatefromfile( 'http://example.net/photo.jpeg?foo=hello&bar=world' );
Here's how it's done:
function imagecreatefromfile( $filename ) {
if (!file_exists($filename)) {
throw new InvalidArgumentException('File "'.$filename.'" not found.');
}
switch ( strtolower( pathinfo( $filename, PATHINFO_EXTENSION ))) {
case 'jpeg':
case 'jpg':
return imagecreatefromjpeg($filename);
break;
case 'png':
return imagecreatefrompng($filename);
break;
case 'gif':
return imagecreatefromgif($filename);
break;
default:
throw new InvalidArgumentException('File "'.$filename.'" is not valid jpg, png or gif image.');
break;
}
}
With some small modifications to switch
same function is ready for web url's:
/* if (!file_exists($filename)) {
throw new InvalidArgumentException('File "'.$filename.'" not found.');
} <== This needs addiotional checks if using non local picture */
switch ( strtolower( array_pop( explode('.', substr($filename, 0, strpos($filename, '?'))))) ) {
case 'jpeg':
After that you can use it with http://www.tld/image.jpg
:
$jpeg_image = imagecreatefromfile( 'http://example.net/photo.jpeg' );
$gif_image = imagecreatefromfile( 'http://www.example.com/art.gif?param=23&another=yes' );
Some proofs:
As you can read from official PHP manual function.imagecreatefromjpeg.php GD allows loading images from URLs that is supported by function.fopen.php, so there is no need to fetch image first and save it to file, and open that file.
How do you find the filetype of an image in a url with nonobvious filetype in Python
Building on the responses to this question, you could try:
import requests
from PIL import Image # pillow package
from io import BytesIO
url = "your link"
image = Image.open( BytesIO( requests.get( url ).content))
file_type = image.format
This calls for downloading the entire file, though. If you're looking to do this in bulk, you might want to explore the option in the comment above that mentions "magic bytes"...
Edit:
You can also try to get the image type from the headers of the response to your url:
headers = requests.get(url).headers
file_type =headers.get('Content-Type', "nope/nope").split("/")[1]
# Will print 'nope' if 'Content-Type' header isn't found
print(file_type)
# Will print 'gif' or 'jpeg' for your listed urls
Edit 2:
If you're really only concerned with the file type of the link and not the file itself, you could use the head
method instead of the get
method of the requests module. It's faster:
headers = requests.head(url).headers
file_type =headers.get('Content-Type', "nope/nope").split("/")[1]
save any image type from a url as jpg
I guess this is not possible (taking in mind all of the existing image filetypes out there) but for the most basic ones there should be libraries for converting.
Also for the thing you tried - just renaming the file extension to .jpg
doesn't actually make it a jpg (IrfanView, for example, warns you upon opening such file and asks you if you want to change the extension back to correct one)
Linking images regardless of file type
You can do it in CSS like this:
background-image: url('users/avatars/$username.jpg'), url('users/avatars/$username.png');
Getting a file type from URL
Assuming your Content-Type
HTTP headers are accurate, you can avoid downloading the whole file just to check the type by creating a HEAD
request. Assuming you don't also need the whole file for something else, this could be a much-quicker operation, especially for large files.
Working Example:
var xhr = new XMLHttpRequest();xhr.open('HEAD', 'https://crossorigin.me/http://placehold.it/350x150', true);
xhr.onload = function() { var contentType = xhr.getResponseHeader('Content-Type'); console.log(contentType);};
xhr.send();
How to save an image from an URL which does not contain any image file extensions (e.g. png) in Python?
you can get do the following, after getting the response:
_, extension = response.headers["content-type"].split("/")
fname = f"sample_image.{extension}"
file = open(fname, "wb")
file.write(response.content)
file.close()
How can I detect the file type of image at a URL?
Well, https://stackoverflow.com/content/img/so/logo
is a 404. If it were not, then you could use
#!/usr/bin/perl
use strict;
use warnings;
use LWP::Simple;
my ($content_type) = head "https://stackoverflow.com/content/img/so/logo.png";
print "$content_type\n" if defined $content_type;
__END__
As Kent Fredric points out, what the web server tells you about content type need not match the actual content sent by the web server. Keep in mind that File::MMagic can also be fooled.
#!/usr/bin/perl
use strict;
use warnings;
use File::MMagic;
use LWP::UserAgent;
my $mm = File::MMagic->new;
my $ua = LWP::UserAgent->new(
max_size => 1_000 * 1_024,
);
my $res = $ua->get('https://stackoverflow.com/content/img/so/logo.png');
if ( $res->code eq '200' ) {
print $mm->checktype_contents( $res->content );
}
else {
print $res->status_line, "\n";
}
__END__
Determine file extension for image urls
If you can trust that the URLs are not malformed, how about this:
FilenameUtils.getExtension(URI.create(url).getPath())
Related Topics
Function Eregi() Is Deprecated
Display Output in Parts in PHP
Using Regex to Filter Attributes in Xpath with PHP
How to Avoid Code Repetition with PHP SQL Prepared Statements
PHP Object Attribute with Dot in Name
Why PHP Iteration by Reference Returns a Duplicate Last Record
PHP Regex Word Boundary Matching in Utf-8
How to Dynamically Build Queries with Pdo
Using PHP as a Template Engine
Cannot Send Session Cookie - Headers Already Sent
Use Openssl_Encrypt to Replace Mcrypt for 3Des-Ecb Encryption
Performance in Pdo/Php/Mysql: Transaction Versus Direct Execution