Проблема с imagecreatetruecolor
c0dex
web.dev 2002-.
@Ulibka, Call to undefined function imagecreatetruecolor() дальше в гугол
PS: надо убедиться в том, что ты верную строчку нашел и раскомментил и в НУЖНОМ файле. Нету у тебя библиотеки GD
Фанат
oncle terrible
Ulibka
Новичок
Нашел еще параметр , установил
extension_dir = «C:\xampp\php\ext»
Если extension_dir не выставить, то возникает ошибка
PHP Startup: Unable to load dynamic library ‘C:\php\ext\php_gd2.dll’
стоит строка
extension=php_gd2.dll
Ошибки пропали, но картинка все равно не появляется.
Может быть проблема в Xampp ?
P.S. apache я конечно перезагружал
c0dex
web.dev 2002-.
@Ulibka, тебя не смущает:
c0dex
web.dev 2002-.
Ulibka
Новичок
Смущает
Xampp поставил на SSD (диск F)
PHP стоит на F:\xampp\php
В директории F:\xampp\php\ лежит php.ini
Пробовал ставить
extension_dir = F:/xampp/php/ext
Программа не работает (картинки не видно)
Снес xampp, поставил на C: Apache (httpd-2.4.29-Win64-VC15 from Apache lounge)
Поставил на C: в директорию PHP сам php 7 (php-7.2.1-Win32-VC15-x64 thread safe.zip)
Выставил
extension_dir = c:/php/ext
та же фигня — не работает
Ulibka
Новичок
Может быть я все таки в пяти строках программы ошибся ?
Но ведь это я тупо записал пример (наверно даже из документации)
Источник
Проблема с imagecreatetruecolor
Cramac
Новичок
Проблема с imagecreatetruecolor
Не работает функция imagecreatetruecolor. В чем дело?
Возможно надо ГД2, если да, то где скачать под винды?
Стоит ВинХП, ГД1.6.2.
Фанат
oncle terrible
Sapfir
Guest
Повторяй за мной:
1). Иди в папку где у тебя распакован php.
2). Там открой папку extensions. В ней найди файл php_gd2.dll. Копируй его
3). Иди в папку где УСТАНОВЛЕН РНР (предположительно C:\php3 или С:\php4) и вставляй туда файл.
4). Открой свой php.ini (в папке Windows) найди строчку ;extension=php_gd2.dll и убери знак «;» в начале.
5). Улыбайся, радуйся.
Cramac
Новичок
Фанат
oncle terrible
Cramac
Новичок
Одну проблему решил, теперь другая, перестал работать вот такой скриптик:
header («Content-type: image/JPEG»);
$org_h = imagesy($src );
$org_w = imagesx($src );
if($org_h > $org_w ) <
$x_img=»800″;
$x_k= ($x_img * 100) / $org_h;
> else <
$y_img=»800″;
$y_k= ($y_img * 100) / $org_w;
>
if ($x_img==»»)<$x_img= ($org_h * $y_k)/100;>
else <$y_img=($org_w * $x_k)/100;>
// height is bigger than width
$cfg[height] = $x_img;
$cfg[width]= floor($cfg[height] * $org_w / $org_h );
$cfg[dstX]= ($y_img — $cfg[width]) / 2;
$cfg[dstY]= 0;
> else <
// width is bigger than height
$cfg[width]= $y_img;
$cfg[height] = floor($cfg[width] * $org_h / $org_w );
$cfg[dstX]= 0;
$cfg[dstY]= ($x_img — $cfg[height]) / 2;
>
ImageCopyResized($img, $src, $cfg[dstX], $cfg[dstY], 0, 0, $cfg[width], $cfg[height], $org_w, $org_h );
##################
Imagejpeg($img);
##################
ImageDestroy($img );
при передаче всех данных ничего не происходит, а у хостера работает.
пытаюсь вот так открыть resize.php?name=selk001.jpg
а наме не передается.
Что не так?
ПС. Обновил то быстро, главное чтоб теперь не зря 6.5 мегов скачал.
Источник
imagecreatetruecolor
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)
imagecreatetruecolor — Создание нового полноцветного изображения
Описание
imagecreatetruecolor() возвращает объект, представляющий чёрное изображение заданного размера.
Список параметров
Возвращаемые значения
Возвращает объект изображения в случае успешного выполнения или false в случае возникновения ошибки.
Список изменений
| Версия | Описание |
|---|---|
| 8.0.0 | В случае успешного выполнения функция теперь возвращает экземпляр GDImage ; ранее возвращался ресурс ( resource ). |
Примеры
Пример #1 Создание нового потока GD изображения и вывод картинки.
Результатом выполнения данного примера будет что-то подобное:
Смотрите также
- imagedestroy() — Уничтожение изображения
- imagecreate() — Создание нового палитрового изображения
User Contributed Notes 37 notes
If you want to create a *transparent* PNG image, where the background is fully transparent, and all draw operations happen on-top of this, then do the following:
= imagecreatetruecolor ( 800 , 600 );
imagesavealpha ( $png , true );
$trans_colour = imagecolorallocatealpha ( $png , 0 , 0 , 0 , 127 );
imagefill ( $png , 0 , 0 , $trans_colour );
$red = imagecolorallocate ( $png , 255 , 0 , 0 );
imagefilledellipse ( $png , 400 , 300 , 400 , 300 , $red );
header ( «Content-type: image/png» );
imagepng ( $png );
?>
What you do is create a true colour image, make sure that the alpha save-state is on, then fill the image with a colour that has had its alpha level set to fully transparent (127).
The resulting PNG from the code above will have a red circle on a fully transparent background (drag the image into Photoshop to see for yourself)
HOW THE CHECK THE MEMORY BEFORE CREATING AN IMAGE?
I worked on a script where I delt with large images. Very often the error «out of memory» occured. So I had to figure out, how to check the memory BEFORE creating an image. I didn’t find a solution on the web, so I ran my own test script. It built lots of images to compute the needed memory. I found out, that the formula mem = x * y * channel was not enough. There was an additional multiplier that varied. As a result 1.7 worked best. So the formula is: mem = x * y * channel * 1.7.
I post this script here hoping it is useful to someone who will run into the same problems.
//————————————————— ENOUGH MEMORY ?
function enoughmem ( $x , $y , $rgb = 3 ) <
return ( $x * $y * $rgb * 1.7 MAXMEM — memory_get_usage () );
>
//————————————————— SIMPLE EXAMPLE
list ( $x , $y ) = @ getimagesize ( ‘your_img.jpg’ ); //— get size of img —
if ( enoughmem ( $x , $y )) <
$img = @ imagecreatefromjpeg ( ‘your_img.jpg’ ); //— open img file —
$thumb = 200 ; //— max. size of thumb —
if ( $x > $y ) <
$tx = $thumb ; //— landscape —
$ty = round ( $thumb / $x * $y );
> else <
$tx = round ( $thumb / $y * $x ); //— portrait —
$ty = $thumb ;
>
if ( enoughmem ( $tx , $ty )) <
$thb = imagecreatetruecolor ( $tx , $ty ); //— create thumbnail —
imagecopyresampled ( $thb , $img , 0 , 0 , 0 , 0 , $tx , $ty , $x , $y );
imagejpeg ( $thb , ‘your_thumbnail.jpg’ , 80 );
imagedestroy ( $thb );
>
imagedestroy ( $img );
>
//—————————————————
//— to check the memory working with —
//— b/w-image or gif use: —
//—————————————————
$check = enoughmem ( $x , $y , 1 );
?>
Taking the opportunity, I thank everyone here at php.net for the great manual and the useful user scripts.
using imagecolorallocate to specify the image’s background color does not work with truecolor-image.
instead you have to use imagefill to force flood-filling the image with the backgorund-color previously allocated:
$bgColor = imagecolorallocate($img, 255,255,255);
imagefill($img , 0,0 , $bgColor);
There is no need to allocate colors with imagecreatetruecolor. All [256 x 256 x 256 x 128] true colors are already allocated, and you can use the color indexes directly.
Examples :
Blue => color index 255.
White => color index 16777215 (= 255*256² + 255*256+255).
Full transparent => color index 2130706432 (= 127*256^3).
If you want to place an image on a larger canvas you’ve previously created with imagecreatetruecolor(), but you don’t want the default black background to surround it: use imagefill() AFTER imagecopyresampled().
I have no idea why this should be the case, but it works!
A note to post by Justin Greer @ 18-Nov-2003 10:40:
While this information has already been posted by php at REMOVEreallynicejerk dot com @ 16-Sep-2002 12:01, I feel it neccesary to notice ’cause Justin’s post is in the top and it can make people go the wrong way: Justin’s way of detecting which imagecreate function to use is too complicated, while there’s an easy standard way:
if ( function_exists ( ‘imagecreatetruecolor’ ) <
// use imagecreatetruecolor
> else <
// use imagecreate
>
If you want a simple way to mirror images, use the function I’ve included below.
function image_mirror ( $input_image_resource )
<
$width = imagesx ( $input_image_resource );
$height = imagesy ( $input_image_resource );
$output_image_resource = imagecreatetruecolor ( $width , $height );
$y = 1 ;
while ( $y $height )
<
for ( $i = 1 ; $i $width ; $i ++ )
imagesetpixel ( $output_image_resource , $i , $y , imagecolorat ( $input_image_resource , ( $i ), ( $height — $y ) ) );
$y = $y + 1 ;
>
return $output_image_resource ;
>
?>
Example Usage:
// A good use of this is when a user uploads a TGA file,
// on the completion screen show the image and have a link
// that asks if the image appears mirrored, and if so
// that link will execute these commands below.
// I suggest checking $HTTP_REFERER for security.
// $_GET[‘file’] in this case would be something along the lines
// of johndoe-img0001 (Basename is necessary to prevent
// abuse of this script!)
if ( isset( $_GET [ ‘file’ ] ) )
<
$filename = «./» . basename ( $_GET [ ‘file’ ] ) . «.jpg» ;
// Making the image resource that needs to be mirrored
// Taking it from a previously exported to JPEG file.
$output_resource_image = image_mirror ( imagecreatefromjpeg ( $filename ) );
if ( imagejpeg ( $output_resource_image , $filename , 75 ) )
echo «Image resaved successfully» ;
else
echo «Image couldn’t be written over (Check permissions)!» ;
>
?>
Unfortunately the @imagecreatetruecolor() method doesn’t even work because php dies with a fatal error noting that GD 2 is required. You can’t even capture this error with a custom error handler.
I have come up with a function to get the GD version number that seems to work pretty well on every version of PHP and GD I’ve thrown at it (even CLI versions.) It’s obviously not the most efficient thing in the world, but it does cache the result in a static variable so calling it multiple times doesn’t slow down further.
function gd_version() <
static $gd_version_number = null;
if ($gd_version_number === null) <
// Use output buffering to get results from phpinfo()
// without disturbing the page we’re in. Output
// buffering is «stackable» so we don’t even have to
// worry about previous or encompassing buffering.
ob_start();
phpinfo(8);
$module_info = ob_get_contents();
ob_end_clean();
if (preg_match(«/\bgd\s+version\b[^\d\n\r]+?([\d\.]+)/i»,
$module_info,$matches)) <
$gd_version_number = $matches[1];
> else <
$gd_version_number = 0;
>
>
return $gd_version_number;
>
Then you can simply use it something like this:
if (gd_version() >= 2) <
$image = ImageCreateTrueColor($width, $height);
> else <
$image = ImageCreate($width, $height);
>
I just fiddled around with Phpix, which had some problems using the GD lib
(washed out colours).
I changed the lines, which did the trick.
Just in case some of you are still having problems and
you can’t change the PHP-install
on the hosting side:
$im = ImageCreateFromJPEG($source);
$new_im = ImageCreate($new_width,$new_height);
$im = ImageCreateFromJPEG($source);
$new_im = ImageCreateTrueColor($new_width,$new_height);
Here is my solution for creating images with the same code for both GD 2:
$dst_img = @imageCreateTrueColor($width, $height);
if (!$dst_img)
Because imagecreatetruecolor exist both in gd and gd2,
you can’t use function_exists or get_extension_funcs to check for gd2 !
But . there is a difference in imagettfbbox between gd and gd2:
gd use pixels and gd2 use points.
Then you can check gd2 with this function:
$rep=false;
if(isset($GLOBALS[«gBGDVersion»]))
<
$rep=$GLOBALS[«gBGDVersion»];
>
else
<
if(function_exists(«gd_info»))
<
$gdver=gd_info();
if(strstr($gdver[«GD Version»],»1.»)!=false)
<
$rep=false;
>
else
<
$rep=true;
>
>
else
<
$size=40;
$font= your font file path here;
$b=imagettfbbox ($size,0,$font,»abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ»);
This little function does it for you:
The .299 , .578 , .114 values are estimations, and add a gamma correction to the colors. For more or less luminace in the result, you can change these values.
Goodluck,
Eric Mulders, Netherlands
I put this together — combining two of the examples and then generated the text dynamically. but, with this set up, i was able to get the transparent background working as well.
// Set the content-type
header ( ‘Content-type: image/png’ );
// Create the image
$im = imagecreatetruecolor ( 175 , 15 );
imagesavealpha ( $im , true );
// Create some colors
$white = imagecolorallocate ( $im , 255 , 255 , 255 );
$grey = imagecolorallocate ( $im , 128 , 128 , 128 );
$black = imagecolorallocate ( $im , 0 , 0 , 0 );
imagefilledrectangle ( $im , 0 , 0 , 150 , 25 , $black );
$trans_colour = imagecolorallocatealpha ( $im , 0 , 0 , 0 , 127 );
imagefill ( $im , 0 , 0 , $trans_colour );
// The text to draw
$text = $_GET [ ‘text’ ];
// Replace path by your own font path
$font = ‘catriel regular.ttf’ ;
// Add some shadow to the text
imagettftext ( $im , 9 , 0 , 13 , 16 , $black , $font , $text );
// Add the text
imagettftext ( $im , 9 , 0 , 12 , 15 , $white , $font , $text );
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng ( $im );
imagedestroy ( $im );
?>
imagecreatetruecolor() returns not only image identifier representing a black image of size x_size by y_size.
imagecreatetruecolor() is called to create truecolor images, with an essentially unlimited number of colors (also not only 256 colors).
Thanks to OverFlow636 at gmail dot com and kuya1284 at techie dot com for their original coding which this function is based upon.
PHP lacks an imagecreatefromtga function, so I have prepared a simple function to include in your library if you deal with TGA images. In addition to creating an image from TGA, it also, optionally, will output an array with the dimensions of the image because getimagesize() does not function with TGA files.
Hopefully this function will eventually be unneeded if GD is ever updated to support the TGA format.
Please keep in mind that TGA’s come in many different compressions, color settings, and as a result this function will not work 100% of the time. Resulting images will fit the symptoms kuya1284 at techie dot com mentioned, and as a result you may need to create a second function. Keep in mind that using her code causes the «mirror» effect on images that load properly with the following function.
function imagecreatefromtga ( $filename , $return_array = 0 )
<
$handle = fopen ( $filename , ‘rb’ );
$data = fread ( $handle , filesize ( $filename ) );
fclose ( $handle );
$pointer = 18 ;
$x = 0 ;
$y = 0 ;
$w = base_convert ( bin2hex ( strrev ( substr ( $data , 12 , 2 ) ) ), 16 , 10 );
$h = base_convert ( bin2hex ( strrev ( substr ( $data , 14 , 2 ) ) ), 16 , 10 );
$img = imagecreatetruecolor ( $w , $h );
while ( $pointer strlen ( $data ) )
<
imagesetpixel ( $img , $x , $y , base_convert ( bin2hex ( strrev ( substr ( $data , $pointer , 3 ) ) ), 16 , 10 ) );
$x ++;
if ( $return_array )
return array ( $img , $w , $h );
else
return $img ;
>
?>
Example Usage
// the image ( resource image )
$image = $array [ 0 ];
// its dimensions ( integers )
$dimensions [ ‘width’ ] = $array [ 1 ];
$dimensions [ ‘height’ ] = $array [ 2 ];
// Delete the image resource array entry to free memory
imagedestroy ( $array [ 0 ]);
?>
The second variable, $return_array is optional. If you simply want to load a TGA, leave the variable off the function’s call as such:
Источник