php create image from image
imagecreatefromstring
(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)
imagecreatefromstring — Создание нового изображения из потока представленного строкой
Описание
Список параметров
Строка содержащая данные изображения.
Возвращаемые значения
Ошибки
imagecreatefromstring() вызывает ошибку уровня E_WARNING, если данные в неподдерживаемом формате.
Список изменений
Версия | Описание |
---|---|
8.0.0 | В случае успешного выполнения функция теперь возвращает экземпляр GDImage ; ранее возвращался ресурс ( resource ). |
7.3.0 | Добавлена поддержка WEBP (если поддерживается используемой libgd). |
Примеры
Пример #1 Пример использования imagecreatefromstring()
Результатом выполнения данного примера будет что-то подобное:
Смотрите также
User Contributed Notes 17 notes
While downloading images from internet, it’s easiest to let php decide what is the file type. So, forget using imagecreatefromjpg, imagecreatefromgif and imagecreatefrompng. Instead, this is the way to go:
My site allows anonymous uploads to a web-accessible location (that will execute a script if it finds one).
Naturally, I need to verify that only harmless content is accepted. I am expecting only images, so I use:
So you guys don’t spend an hour trying to figure out why your script keeps running out of memory when you’re using this or the other imagecreatefrom functions. GD uncompresses the image when you use these functions, and this can lead to your script running out of memory.
If you download a rawimage save it on your computer to jpeg so the file size comes down, GD will automatically convert it to the raw and you can possibly run out of memory.
[Editor’s note: BMP will be supported as of PHP 7.2.0.]
In case it’s not obvious from the lack of «imagecreatefrombmp()» in GD, this function cannot handle plain old BMP files either.
I know a lot of people have been having trouble using images from the Sprint PPC6700 with GD. The jpeg library always thows an error about 16 bytes of extraneous data. I decided to poke around in a hex editor and found those extraneous bytes occur right at the end of the exif data.
By removing this extraneous data, images can easily be manipulated by GD and the EXIF extension as a normal images. This also removes any problems using the images with GIMP which must rely on the same jpeg libraries.
Here is a function that will check to see if an image is from the PPC6700 and then remove the extraneous data for you. The result can successully be used with imagecreatefromstring
Author: Paul Visco
IM: paulsidekick
Created: 2-12-06
//get the file contents
$data = file_get_contents($orig);
I use dynamically generated images that require a little touch-up before being displayed. So essentially I do some base work, then store the images in a memory cache (APC), reload the images again from the cache later on «into» GD, do final processing and then display the image.
Since I wanted to avoid a lot of disc access I used the output buffering functions:
// Do your image processing stuff
// Put stuff into cache
// Do final editing stuff and output image
?>
Of course this is a condensed example but I just wanted to share the idea.
An easy example to help understanding this function.
The function will try to auto-determine file format (jpg, gif, png. ), and will return false if fails.
Create an image resource from file, without knowing image type:
A note to the previous question (if you still don’t know it :)).
GIF’s are 256 colors (or 8 bit), and the resample function needs true color I guess. that’s why it works with JPG’s and not with GIF’s.
Next thing. you take a string, write it to file, open the file (imagecreatefromgif), and delete the file again.
if you do imagecreatefromstring($string) you can skip the temporary file part.
If you let them, the PHP function will return an error «Data is not in a recognized format in».
If you have this situation :
$image_string=str_replace(«data:image/png;base64,»,»»,$image_string);
$image_string = base64_decode($image_string);
$img = imagecreatefromstring($image_string);
I run a blogging site that allowed users to publish images from their cell phones. For some reason, the nokia 3220 produces jpegs with extrandeous data before the EOF 0xFFF9
I wrote this class to allow you to fix the images so that they can be used with GD to resize and manipulate. Without applying the fix both GD and gimp report errors for the file. If basically keeps eating bytes from the junk part till the file is a valid jpeg. Here is an example bunk pic written by a nokia 3220 that you cna test it with http://www.shawnrider.com/moblog/cache/0854747001121624103.jpg
/*
Author: Paul Visco
Hompage: http://www.elmwoodstrip.com?u=paul
AIM: paulsidekick
Notes: The file allows you fix the jpegs created by the Nokia 3220 picture phone so that they can be manipulated using the GD library with PHP.
Usage: Simply instanitiate the class and then call the fix method for each image.
e.g.
$nokia = new nokia;
$nokia->debug =»y»;
$nokia->fix(«yourpic.jpg»);
*/
//load the file into a string
$this->str = file_get_contents($this->file);
//test to see if it is a nokia image or if it has been corrupted previously
if (substr_count($this->str, chr(0x28).chr(0x36).chr(0x28).chr(0x2B)) == 0 || @imagecreatefromstring($this->str))
<
if ($this->debug ==»y»)
<
echo «\n
«.$this->file.» is not a corrupted Nokia pic»;
>
//strip out the funk e crap from the file
$this->eat($this->str);
//return true for fixed
return true;
//check the image
$this->img = @imagecreatefromstring($this->str);
//check the image again
$this->img = @imagecreatefromstring($this->str);
>
if ($this->debug ==»y»)
<
//notify the user it’s fixed
echo «\n
Nasty bits eaten!! «.$this->file.» is fixed now thanks to p:labs!»;
>
return true;
>
The only way I managed to resolve the loading of image files from file data either on local site or from off-site protocols is as follows. I hope this saves someone else the two hours of debugging and looking for good examples.
[PHP]
Here is the code I did to create a thumbnail image from the database blob field. The trick is to use «imagecreatefromstring()» to create an image file.
imagecreatefrompng
(PHP 4, PHP 5, PHP 7, PHP 8)
imagecreatefrompng — Создаёт новое изображение из файла или URL
Описание
imagecreatefrompng() возвращает идентификатор изображения, представляющего изображение полученное из файла с заданным именем.
Список параметров
Путь к изображению PNG.
Возвращаемые значения
Возвращает объект изображения в случае успешного выполнения или false в случае возникновения ошибки.
Список изменений
Версия | Описание |
---|---|
8.0.0 | В случае успешного выполнения функция теперь возвращает экземпляр GDImage ; ранее возвращался ресурс ( resource ). |
Примеры
Пример #1 Пример обработки ошибки при загрузке PNG
header ( ‘Content-Type: image/png’ );
$img = LoadPNG ( ‘bogus.image’ );
Результатом выполнения данного примера будет что-то подобное:
User Contributed Notes 7 notes
If you’re trying to load a translucent png-24 image but are finding an absence of transparency (like it’s black), you need to enable alpha channel AND save the setting. I’m new to GD and it took me almost two hours to figure this out.
I had the same problem as jboyd1189 at yahoo dot com but I solve d it allocating more memory dynamically.
The approach I used to solve the problem is:
1-Calculate the memory required by the image
2-Set the new memory_limit value
3-Create the PNG image and thumbnail
4-Restore the original value
Because gd and imagick do not support animated PNG (at this moment), i wrote a simple function to determine if given PNG is APNG or not. It does not validate PNG, only checks whenever «acTL» chunk appears before «IDAT» like the specification says: https://wiki.mozilla.org/APNG_Specification
When using imagecreatepng with alpha blending you will lose the blending.
This will create a true colour image then copy the png image to this true colour image and retain alpha blending.
imagecreatefromjpeg
(PHP 4, PHP 5, PHP 7, PHP 8)
imagecreatefromjpeg — Create a new image from file or URL
Description
imagecreatefromjpeg() returns an image identifier representing the image obtained from the given filename.
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
Parameters
Path to the JPEG image.
Return Values
Returns an image object on success, false on errors.
Changelog
Version | Description |
---|---|
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned. |
Examples
Example #1 Example to handle an error during loading of a JPEG
header ( ‘Content-Type: image/jpeg’ );
$img = LoadJpeg ( ‘bogus.image’ );
The above example will output something similar to:
User Contributed Notes 34 notes
This function does not honour EXIF orientation data. Pictures that are rotated using EXIF, will show up in the original orientation after being handled by imagecreatefromjpeg(). Below is a function to create an image from JPEG while honouring EXIF orientation data.
This little function allows you to create an image based on the popular image types without worrying about what it is:
If imagecreatefromjpeg() fails with «PHP Fatal error: Call to undefined function: imagecreatefromjpeg()», it does NOT necessarily mean that you don’t have GD installed.
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: ‘image.jpg’ is not a valid JPEG file
This only happens with certain images, which when opened in any program are ok, it even uploads to the version of the site I have on localhost with no problems,
To fix try below code snippet-
In John’s human readable code version of Karolis code to dynimicly allocate need memory there are a few bugs. If you didn’t compile with the «—enable-memory-limit» option, this script will error with a level E_ERROR. Bellow is a fixed version rapped as a function. To view replacement functions for memory_get_usage() look at http://us2.php.net/manual/en/function.memory-get-usage.php
did you found that sometimes it hang the php when imagecreatefromjpeg() run on bad JPEG. I found that this is cause by the JPEG file U used dont have EOI (end of image)
the FF D9 at the end of your JPEG
JPEG image should start with 0xFFD8 and end with 0xFFD9
Tips for Windows User to Set up GD(dynamic graphic lib) with PHP.
When i run following function, which terminates at
error message is : undefined function imagecreatefromjpeg();
no other code of the script gets executed.
In one word, you need to turn on gd lib,
which hold the implementation of imagecreatefromjpeg();
please follow below steps:
my php install dir is: c:/php/
first you must try to find:
c:/php/php.ini
c:/php/ext/php_gd2.dll(php 5)
c:/php/extension/php_gd2.dll(php 4)
The php_gd2.dll is included in a standard PHP installation for Windows,
however, it’s not enabled by default.
You have to turn it on,
You may simply uncomment the line «extension=php_gd2.dll» in php.ini and restart the PHP extension.
You may also have to correct the extension directory setting
from:
extension_dir = «./»
extension_dir = «./extensions»
To (FOR WINDOWS):
extension_dir = «c:/php/extensions»(php 4)
extension_dir = «c:/php/ext»(php 5)
This will clean up unnecessary jpeg header information which can cause trouble. Some cameras or applications write binary data into the headers which may result in ugly results such as strange colors when you resample the image later on.
This is from the jhead documentation: «-purejpg: Delete all JPEG sections that aren’t necessary for rendering the image. Strips any metadata that various applications may have left in the image.»
jhead got some other useful options as well.
Last night I posted the following note under move_upload_file and looked tonight to see if it got into the system. I happen to also pull up imagecreatefromjpeg and got reminded of many resize scripts in this section. Unfortunately, my experience was not covered by most of the examples below because each of them assumed less than obvious requirements of the server and browser. So here is the post again under this section to help others uncover the mystery in file uploading and resizing arbitrary sized images. I have been testing for several days with hundreds of various size images and it seems to work well. Many additional features could be added such as transparency, alpha blending, camera specific knowledge, more error checking. Best of luck.
I have for a couple of years been stymed to understand how to effectively load images (of more than 2MB) and then create thumbnails. My note below on general file uploading was an early hint of some of the system default limitations and I have recently discovered the final limit I offer this as an example of the various missing pieces of information to successfully load images of more than 2MB and then create thumbnails. This particular example assumes a picture of a user is being uploaded and because of browser caching needs a unique number at the end to make the browser load a new picture for review at the time of upload. The overall calling program I am using is a Flex based application which calls this php file to upload user thumbnails.
The secret sauce is:
1. adjust server memory size, file upload size, and post size
2. convert image to standard formate (in this case jpg) and scale
htaccess file:
php_value post_max_size 16M
php_value upload_max_filesize 6M
imagecreatefromgif
(PHP 4, PHP 5, PHP 7, PHP 8)
imagecreatefromgif — Создаёт новое изображение из файла или URL
Описание
imagecreatefromgif() возвращает объект изображения, представляющего изображение полученное из файла с заданным именем.
Список параметров
Путь к GIF картинке.
Возвращаемые значения
Возвращает объект изображения в случае успешного выполнения или false в случае возникновения ошибки.
Список изменений
Версия | Описание |
---|---|
8.0.0 | В случае успешного выполнения функция теперь возвращает экземпляр GDImage ; ранее возвращался ресурс ( resource ). |
Примеры
Пример #1 Пример обработки ошибки при загрузке GIF
header ( ‘Content-Type: image/gif’ );
$img = LoadGif ( ‘bogus.image’ );
Результатом выполнения данного примера будет что-то подобное:
Примечания
Поддержка GIF была убрана из GD библиотеки в версии 1.6, и добавлена обратно в версии 2.0.28. Эта функция недоступна в промежуточных версиях.
User Contributed Notes 20 notes
An updated is_ani based on issues reported here and elsewhere
I hate created an improved version of frank at huddler dot com’s is_ani function, which keeps score even between hunks. Hope this helps!
$totalCount = 0;
$chunk = »;
I wanted to find out if a GIF is Black & White or Color, but I didn’t want to wait around for imagecreatefromgif() to parse a 200k file (about 1 second) to get the color map, so I wrote this function to get a list of all the colors in the GIF. Hope it is useful for you.
I have written this code to detect if a gif file is animated or not. I thought I would share it 🙂
Hopefully this might save someone a headache when using functions to check for animated GIFs.
I have come across some some GIFs use the a different frame separator sequence, \x00\x21, instead of the official standard \x00\x2C. This seems to be happening with animated GIFs saved in Photoshop CS5, although I’m not quite sure if that’s where the issue is originating from.
Anyway, I’ve been using the pattern:
«#\x00\x21\xF9\x04.<4>\x00(\x2C|\x21)#s»
which seems to cover all GIFs, hopefully without misinterpreting.
Just realised that some of the animated GIFs do not contain GCE (graphic control extension). Here is the refactored is_ani() function:
If GD doesn’t support GIFs & gif2png is not available & you are not an administrator, you can install it in your account like this:
imagejpeg
(PHP 4, PHP 5, PHP 7, PHP 8)
imagejpeg — Output image to browser or file
Description
Parameters
Return Values
Returns true on success or false on failure.
Changelog
Version | Description |
---|---|
8.0.0 | image expects a GdImage instance now; previously, a resource was expected. |
Examples
Example #1 Outputting a JPEG image to the browser
The above example will output something similar to:
Example #2 Saving a JPEG image to a file
Example #3 Outputting the image at 75% quality to the browser
Notes
See Also
User Contributed Notes 34 notes
I didn’t find any example like this on the Web, so I mixed pieces together.. hope this will save time to other people!
Here’s a complete solution to READ any image (gif jpg png) from the FILESYSTEM, SCALE it to a max width/height, SAVE the scaled image to a BLOB field keeping the original image type. Quite tricky..
/*
* imageXXX() only has two options, save as a file, or send to the browser.
* It does not provide you the oppurtunity to manipulate the final GIF/JPG/PNG file stream
* So I start the output buffering, use imageXXX() to output the data stream to the browser,
* get the contents of the stream, and use clean to silently discard the buffered contents.
*/
ob_start ();
?>
So, let’s suppose you have a form where a user can upload an image, and you have to scale it and save it into your database.
[..] // the user has clicked the Submit button..
[[Editor’s note: removed the header()-call since it is not required when outputting inline image-data]]
One single code line, solve-me after 3 hours of blind search!
echo » «; //saviour line!
I worked out a script that allows the transfer of alphanumeric data to be placed on an image. The HTML feature is img src and the php feature is imagettftext. This simple code will increment from 1 to 3 on images.
Regarding Carl Gieringer’s comment, it is possible to have PHP files in utf-8. Just make sure the editor does not output BOM, which is unnecessary in utf-8 anyway.
Except for any editors from Microsoft, most programmer’s editors that supports utf allows you to surpress BOM.
With regard to chris.calo’s code:
It assumes more than that, namely that the filename does not contain the strings ‘.gif’, ‘.jpg’, ‘.jpeg’, ‘.bmp’, or ‘.png’ *anywhere* in the string. Some valid files with special filenames could break this; for example, a file named «used.to.be.a.png.file.gif» would cause this script to attempt to load the file as a PNG. Obviously this is a rare case, but the issue could be easily avoided by using «else ifs» (uses less CPU time) or checking that the extension abuts the end of the string or both.
That said, the whole business could be avoided if PHP didn’t clutter the namespace with different functions to do the same thing with different image formats. Ick.
note below is missing «()» from the ob_end_clean call:
ob_end_clean; // stop this output buffer
ob_end_clean(); // stop this output buffer
You can then use this for adding content-length headers (for example flash requires a content length in advance to create loaders)
For those looking to grab the resolution of a JPEG image without using GD nor ImageMagic. I wrote this simple function.
Too bad GD doesn’t have this very simple function for us to use.
I had a problem with denied permissions when trying to upload AND resize an image having safe_mode on. This caused that I couldn’t create the new file in which I wanted to resampled the image with nor with imagejpeg() nor with touch() and imagejpeg() after it.
Here is my solution, I didn’t test, but it’s possible, it is biting some memory:
?>
As you can see, the function moves the uploaded file where you want to save the resampled image (move_uploaded_file is not restricted by safe_mode) and then you can resample the image, because it was created by moving it already.
Note: the directory where you want to save the file must have permissions set to 0777.
Anything over 80 results in an unnecessary increase in file size without much increase in image quality.
I had similar problem with safe mode. My solution is:
before imagejpeg(), touch() etc.
write:
ini_set(safe_mode,Off);
and after everything:
ini_set(safe_mode,On);
strange, but it works
Chears2All
If you wish to capture the jpg data into a variable, rather than outputting it or saving it into a file (perhaps so you can put it in a database), you might want to consider output buffering. Something along these lines should work:
I came here looking for something similar to the getJPEGresolution function, but noticed the drawbacks that were pointed out in the last post. So, after drawing on some other code examples on the web, I put together the following function which should always properly return the correct values. (But remember that you still need to have the EXIF extension installed with your instance of PHP for this to work!)
?>
This function returns an array with the x-resolution, y-resolution when they can be determined, otherwise FALSE.
Take to heart that CAUTION note on this function. If gdlib fails to output, it still returns true! I’d call that a bug personally.
GD will fail to output if you have an image exceeding its maximum undisclosed dimensions of 65500 pixels.
You’ll get a zero byte file instead
Here is a function to resize an image and maintain aspect ratio. It will resize jpeg, gif or png and could easily be modified to add bmp. The name field is the destination of the file minus the file extension:
Please note that there is a bug report open for the currently broken safe_mode behaviour on this function:
According to the PHP staffer who has responded the docs are wrong (I don’t agree but I’m also not their employee).
The work around is to use touch() (or any other file system function that can do this) to create the file first before using imagejpeg().
A word of warning when outputting images to the browser.
Make sure there is no extra spaces around the tags, in the file you are editing, and also any included files.
I began to think there was a bug in GD or something, and I checked the file I was working on, but forgot about the includes.
Rather than using the temporary file, as described above, you can buffer the output stream. Someone else showed me this, and it seems to work very nicely.
//Start buffering the output stream
ob_start();
// output the image as a file to the output stream
Imagejpeg($im);
//Read the output buffer
$buffer = ob_get_contents();
//clear the buffer
ob_end_clean();
[Editor’s note: fixed according to the note of roberto at ilpiola.it]
// Change DPI
$dpi_x = 150 ;
$dpi_y = 150 ;
Don’t forget that JPEG compression has artifacts! And they’re not all really obvious. The PHP JPEG compression is pretty decent, but it seems to generally:
-Lighten the image overall, by a reasonable amount (never seen this before, but it will drive graphic designers crazy, you might want to darken the image before compressing it)
-Reduce saturation, especially with images with lots of points of different color within a few pixels of each other (this is a documented feature of JPEG)
-Seriously mess with blue colors, which is common to all JPEG but really annoying in some situations with blue and black or other detailed blue parts
You might want to consider using imagepng() and outputting a PNG image instead of a JPEG if any of the above affect you, or your image is not very photo-like. Sometimes I have an algorithm compare JPEG to PNG for an image and send the smaller version to the user.
Also, when using imagepng(), you should use imageinterlace() before it 95% of the time. Interlaced JPEGs load progressively, improving in quality as the image loads, so users on slower connections see the whole image at low quality. All this happens without affecting the file size (actually, sometimes the file size is smaller!) or final quality.
Hope this helps a few people out. It’s not all that obvious without lots of playing around.
Don’t be like me racking my brain for hours trying to figure out why my xxx.php file outputs http://localhost/xxx.php as a one line response.
Most likely, you have either:
1. whitespaces before or after the php tags
2. need to set header(‘Content-type: image/jpeg’);
3. if you have required files. be sure nothing is outputted. no test print statements because page expects image information
4. there is an error in your code
in my case, it was 4. there is a reason why the function call base64decode does not work.
it’s actually: base64_decode()
by the way, other ways to validate your image encoded in base64 is to use the following tag:
I was pulling a blob encoded base 64 data from mysql database and trying to render it on a page
hope this helps someone.
Here’s another on-the-fly thumbnail creation script.
When I scripted the pictuerviewer on my page, I had all the pictures only in full size and qualit, because I wanted the posibility für visitors to download the pictures.
But as Imagesizes of more than 4 MP are to large for websites, I created thumbnails and the smaller pictures on the fly. But I found out, that the Script needed too much RAM, especially in the thumbnail overview, when I had more then 50 thumbnails to create on the fly at the same time.
So I modified my image creator and my viewer to let them store images, that are created. So only the first visitor has to wait (which is usually me for controlling the uploads und updates), all other visitors get the stored images, which is much faster.
Create different folders. I have a main folder called ‘imagesdb’ and the tree subfolders full (Full quality images), show (images for the picture viewer) and thumb (for thumbnails in overview).
Store the script for example as image.php and link it like that:
// Now set the maximum sizes to the different styles.
// You may set additional styles, but remember to
// create the according subfolders.
header ( «Content-type: image/jpeg» );
?>
As this website helped me for several times in the past and for creating this script, I hope I can help others with this script saving the time for developing a much more performant solution than an allways-on-the-fly-creating script.