update page now

imagecreatefromstring

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

imagecreatefromstring Создаёт новое изображение из представленного строкой потока

Описание

imagecreatefromstring(string $data): GdImage|false

Функция imagecreatefromstring() возвращает идентификатор изображения, которое функция получила из параметра data. PHP-сборка, если поддерживает, будет автоматически определять типы изображений: JPEG, PNG, GIF, BMP, WBMP, GD2, WEBP и AVIF.

Список параметров

data

Строка, которая содержит данные изображения.

Возвращаемые значения

Функция вернёт объект изображения, если выполнилась успешно. Функция вернёт false, если модуль не поддерживает тип изображения, не распознаёт формат данных или изображение повреждено и загружается.

Ошибки

Функция imagecreatefromstring() выдаёт ошибку уровня E_WARNING, если не распознала формат данных.

Список изменений

Версия Описание
8.0.0 Функция теперь возвращает экземпляр класса GDImage, если выполнилась успешно; раньше функция возвращала ресурс (resource).
7.3.0 Добавили поддержку формата WEBP, если модуль libgd поддерживает такой формат.

Примеры

Пример #1 Пример создания нового изображения функцией imagecreatefromstring()

<?php

$data
= 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg=='
;

$data = base64_decode($data);

$im = imagecreatefromstring($data);

if (
$im !== false) {
header('Content-Type: image/png');
imagepng($im);
} else {
echo
'Возникла ошибка.';
}

?>

Вывод приведённого примера будет похож на:

Вывод примера : imagecreatefromstring()

Смотрите также

  • imagecreatefromjpeg() - Создаёт новое изображение из файла или URL-адреса
  • imagecreatefrompng() - Создаёт новое изображение из файла или URL-адреса
  • imagecreatefromgif() - Создаёт новое изображение из файла или URL-адреса
  • imagecreatetruecolor() - Создаёт новое truecolor-изображение
Добавить

Примечания пользователей 7 notes

up
30
ville dot jungman at gmail dot com
17 years ago
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:

<?php
$src = "http://www.varuste.net/tiedostot/l_ylabanneri.jpg";
$image = imagecreatefromstring(file_get_contents($src));
?>
up
9
php dot net at phor dot net
16 years ago
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:

<?php
  $im = $imagecreatefromstring($USERFILE);
  $valid = ($im != FALSE);
  imagedestroy($im);
  return $valid;
?>
up
5
anon at dude dot com
9 years ago
[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.
up
4
chris at haydenwheeler dot com
6 years ago
imagecreatefromstring does not appear to support WebP images (tested on PHP 7.2.10, with GD 2.1.0 and GD WebP support enabled)
up
5
logan at logansbailey dot com
16 years ago
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.
up
2
hope at it-helps dot com
14 years ago
Create an image resource from file, without knowing image type:

<?php
function imagecreatefromfile($imagepath=false) {
    if(!$imagepath || !$is_readable($imagepath) return false;
    return @imagecreatefromstring(file_get_contents($imagepath));
}
$img_resource=imagecreatefromfile($imagepath);
?>
up
1
Blizzke at gmail dot com
18 years ago
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:

<?php
   // Do your image processing stuff
   
   // Start buffering
   ob_start ( );
   ImageGD ( $hImage );
   $sImage = ob_get_contents ( );
   ob_end_clean ( );

   // Put stuff into cache
 
   // Reload from cache and recreate image
   $hImage = imagecreatefromstring ( $sImage );

   // Do final editing stuff and output image
?>

Of course this is a condensed example but I just wanted to share the idea.
To Top