Что такое код imagecreatefromwbmp

Что такое код imagecreatefromwbmp

imagecreatefromwbmp — Create a new image from file or URL

Description resource imagecreatefromwbmp ( string filename)

imagecreatefromwbmp() returns an image identifier representing the image obtained from the given filename.

imagecreatefromwbmp() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error WBMP :

Example 1. Example to handle an error during creation (courtesy vic@zymsys.com)

Note: WBMP support is only available if PHP was compiled against GD-1.8 or later.

Windows versions of PHP prior to PHP 4.3 do not support accessing remote files via this function, even if allow_url_fopen is enabled.

imagecreatefromwbmp — функция PHP

(PHP 4 >= 4.0.1, PHP 5)

imagecreatefromwbmp — Create a new image from file or URL

Description

imagecreatefromwbmp() returns an image identifier representing the image obtained from the given filename.

imagecreatefromwbmp() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error WBMP :

Warning

Пример 1. Example to handle an error during creation

function LoadWBMP ( $imgname )
<
$im = @ imagecreatefromwbmp ( $imgname ); /* Attempt to open */
if (! $im ) < /* See if it failed */
$im = imagecreatetruecolor ( 20 , 20 ); /* Create a blank image */
$bgc = imagecolorallocate ( $im , 255 , 255 , 255 );
$tc = imagecolorallocate ( $im , 0 , 0 , 0 );
imagefilledrectangle ( $im , 0 , 0 , 10 , 10 , $bgc );
/* Output an errmsg */
imagestring ( $im , 1 , 5 , 5 , «Error loading $imgname» , $tc );
>
return $im ;
>
?>

Замечание: WBMP support is only available if PHP was compiled against GD-1.8 or later.

Подсказка: Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция «fopen wrappers». Смотрите более подробную информацию об определении имени файла в описании функции fopen() , а также список поддерживаемых протоколов URL в Прил. M.

Версии PHP для Windows до PHP 4.3.0 не поддерживают возможность использования удаленных файлов этой функцией даже в том случае, если опция allow_url_fopen включена.

imagecreatefromwbmp

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

imagecreatefromwbmp — Create a new image from file or URL

Description

imagecreatefromwbmp() 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 WBMP image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Example to handle an error during loading of a WBMP

function LoadWBMP ( $imgname )
<
/* Attempt to open */
$im = @ imagecreatefromwbmp ( $imgname );

/* See if it failed */
if(! $im )
<
/* Create a blank image */
$im = imagecreatetruecolor ( 150 , 30 );
$bgc = imagecolorallocate ( $im , 255 , 255 , 255 );
$tc = imagecolorallocate ( $im , 0 , 0 , 0 );

imagefilledrectangle ( $im , 0 , 0 , 150 , 30 , $bgc );

/* Output an error message */
imagestring ( $im , 1 , 5 , 5 , ‘Error loading ‘ . $imgname , $tc );
>

header ( ‘Content-Type: image/vnd.wap.wbmp’ );

$img = LoadWBMP ( ‘bogus.image’ );

imagewbmp ( $img );
imagedestroy ( $img );
?>

User Contributed Notes 4 notes

.bmp is just hex encoded RGB values.
All you need to do is open in binary mode and seperate the header from the body.
Decode the width and height from the header.
Then create the image pixel by pixel from the RGB values in the body.

function imagecreatefrombmp( $filename )
<
$file = fopen( $filename, «rb» );
$read = fread( $file, 10 );
while( !feof( $file ) && $read != «» )
<
$read .= fread( $file, 1024 );
>
$temp = unpack( «H*», $read );
$hex = $temp[1];
$header = substr( $hex, 0, 104 );
$body = str_split( substr( $hex, 108 ), 6 );
if( substr( $header, 0, 4 ) == «424d» )
<
$header = substr( $header, 4 );
// Remove some stuff?
$header = substr( $header, 32 );
// Get the width
$w > // Remove some stuff?
$header = substr( $header, 8 );
// Get the height
$height = hexdec( substr( $header, 0, 2 ) );
unset( $header );
>
$x = 0;
$y = 1;
$image = imagecreatetruecolor( $width, $height );
foreach( $body as $rgb )
<
$r = hexdec( substr( $rgb, 4, 2 ) );
$g = hexdec( substr( $rgb, 2, 2 ) );
$b = hexdec( substr( $rgb, 0, 2 ) );
$color = imagecolorallocate( $image, $r, $g, $b );
imagesetpixel( $image, $x, $height-$y, $color );
$x++;
if( $x >= $width )
<
$x = 0;
$y++;
>
>
return $image;
>

AeroX created a nice example, but it only works at specific imagesizes because bmp uses fully 32-bit lines. To prevent failures (different colors, pixel-shifting per line), the solution is to skip the padding, inserted after color-pixels on the line. His implementation did cutting the padding into the image-data, causing wrong colors, pixel-shifting per line and also an large memory-consumption.

I improved this script to the next implementation. The readability of a image is checked by a other function, so it doesn’t take part in this script.
Suggestions? Please let me know.

public function imagecreatefrombmp ( $p_sFile )
<
// Load the image into a string
$file = fopen ( $p_sFile , «rb» );
$read = fread ( $file , 10 );
while(! feof ( $file )&&( $read <> «» ))
$read .= fread ( $file , 1024 );

$temp = unpack ( «H*» , $read );
$hex = $temp [ 1 ];
$header = substr ( $hex , 0 , 108 );

// Process the header
// Structure: http://www.fastgraph.com/help/bmp_header_format.html
if ( substr ( $header , 0 , 4 )== «424d» )
<
// Cut it in parts of 2 bytes
$header_parts = str_split ( $header , 2 );

// Get the width 4 bytes
$width = hexdec ( $header_parts [ 19 ]. $header_parts [ 18 ]);

// Get the height 4 bytes
$height = hexdec ( $header_parts [ 23 ]. $header_parts [ 22 ]);

// Unset the header params
unset( $header_parts );
>

// Define starting X and Y
$x = 0 ;
$y = 1 ;

// Create newimage
$image = imagecreatetruecolor ( $width , $height );

// Grab the body from the image
$body = substr ( $hex , 108 );

// Calculate if padding at the end-line is needed
// Divided by two to keep overview.
// 1 byte = 2 HEX-chars
$body_size = ( strlen ( $body )/ 2 );
$header_size = ( $width * $height );

// Use end-line padding? Only when needed
$usePadding = ( $body_size >( $header_size * 3 )+ 4 );

// Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
// Calculate the next DWORD-position in the body
for ( $i = 0 ; $i $body_size ; $i += 3 )
<
// Calculate line-ending and padding
if ( $x >= $width )
<
// If padding needed, ignore image-padding
// Shift i to the ending of the current 32-bit-block
if ( $usePadding )
$i += $width % 4 ;

// Reset horizontal position
$x = 0 ;

// Raise the height-position (bottom-up)
$y ++;

// Reached the image-height? Break the for-loop
if ( $y > $height )
break;
>

// Calculation of the RGB-pixel (defined as BGR in image-data)
// Define $i_pos as absolute position in the body
$i_pos = $i * 2 ;
$r = hexdec ( $body [ $i_pos + 4 ]. $body [ $i_pos + 5 ]);
$g = hexdec ( $body [ $i_pos + 2 ]. $body [ $i_pos + 3 ]);
$b = hexdec ( $body [ $i_pos ]. $body [ $i_pos + 1 ]);

// Calculate and draw the pixel
$color = imagecolorallocate ( $image , $r , $g , $b );
imagesetpixel ( $image , $x , $height — $y , $color );

// Raise the horizontal position
$x ++;
>

// Unset the body / free the memory
unset( $body );

// Return image-object
return $image ;
>
?>

Создает новое изображение из файла или URL

(PHP 5 >= 5.5.0, PHP 7)

imagecreatefromwebp — Создает новое изображение из файла или URL

Описание

imagecreatefromwebp() returns an image identifier representing the image obtained from the given filename.

Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen() . Смотрите также список поддерживаемых оберток URL, их возможности, замечания по использованию и список предопределенных констант в Поддерживаемые протоколы и обработчики (wrappers).

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

Path to the WebP image.

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

Возвращает ресурс изображения в случае успеха, или FALSE в случае ошибки.

Примеры

Пример #1 Convert an WebP image to a jpeg image using imagecreatefromwebp()

Что такое код imagecreatefromwbmp

imagecreatefromwbmp — УПЪДБЈФ ОПЧПЕ ЙЪПВТБЦЕОЙЕ ЙЪ ЖБКМБ ЙМЙ URL.

пРЙУБОЙЕ

resource imagecreatefromwbmp (string filename)

imagecreatefromwbmp() ЧПЪЧТБЭБЕФ ЙДЕОФЙЖЙЛБФПТ ЙЪПВТБЦЕОЙС, РПМХЮЕООПЗП ЙЪ ДБООПЗП ЖБКМБ filename.

imagecreatefromwbmp() ЧПЪЧТБЭБЕФ РХУФХА УФТПЛХ РТЙ ПЫЙВЛЕ. фБЛЦЕ ЧЩЧПДЙФ УППВЭЕОЙЕ ПВ ПЫЙВЛЕ, ЛПФПТПЕ ПФПВТБЦБЕФУС Ч ВТБХЪЕТЕ ЛБЛ ТБЪПТЧБООБС УУЩМЛБ. дМС ПВМЕЗЮЕОЙС ПФМБДЛЙ УМЕДХАЭЙК РТЙНЕТ ЧЩЧЕДЕФ WBMP ПЫЙВЛЙ:

Внимание

рТЙНЕТ 1. пВТБВПФЛБ ПЫЙВЛЙ РТЙ УПЪДБОЙЙ (ВМБЗПДБТЙН vic@zymsys.com)

function LoadWBMP ($imgname) < $im = @imagecreatefromwbmp ($imgname); /* РПРЩФЛБ ПФЛТЩФШ */ if (!$im) < /* РТПЧЕТЙФШ, ХДБЮОП МЙ */ $im = imagecreate (20, 20); /* УПЪДБФШ РХУФПЕ ЙЪПВТБЦЕОЙЕ */ $bgc = imagecolorallocate ($im, 255, 255, 255); $tc = imagecolorallocate ($im, 0, 0, 0); imagefilledrectangle ($im, 0, 0, 10, 10, $bgc); /* ЧЩЧЕУФЙ errmsg */ imagestring ($im, 1, 5, 5, "Error loading $imgname", $tc); >return $im; >

рТЙНЕЮБОЙЕ: РПДДЕТЦЛБ WBMP ДПУФХРОБ ФПМШЛП Ч ФПН УМХЮБЕ, ЕУМЙ PHP ВЩМ УЛПНРЙМЙТПЧБО У GD-1.8 ЙМЙ ОПЧЕЕ.

imagecreatefromwbmp

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

imagecreatefromwbmp — Создает новое изображение из файла или URL

Описание

imagecreatefromwbmp() возвращает идентификатор изображения, представляющего изображение полученное из файла с заданным именем.

Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen() . Смотрите также список поддерживаемых оберток URL, их возможности, замечания по использованию и список предопределенных констант в Поддерживаемые протоколы и обработчики (wrappers).

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

Путь к изображению WBMP.

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

Возвращает ресурс изображения в случае успеха, или FALSE в случае ошибки.

Примеры

Пример #1 Пример обработки ошибки при загрузке WBMP

function LoadWBMP ( $imgname )
<
/* Пытаемся открыть */
$im = @ imagecreatefromwbmp ( $imgname );

/* Если не удалось */
if(! $im )
<
/* Создаем пустое изображение */
$im = imagecreatetruecolor ( 150 , 30 );
$bgc = imagecolorallocate ( $im , 255 , 255 , 255 );
$tc = imagecolorallocate ( $im , 0 , 0 , 0 );

imagefilledrectangle ( $im , 0 , 0 , 150 , 30 , $bgc );

/* Выводим сообщение об ошибке */
imagestring ( $im , 1 , 5 , 5 , ‘Ошибка загрузки ‘ . $imgname , $tc );
>

header ( ‘Content-Type: image/vnd.wap.wbmp’ );

$img = LoadWBMP ( ‘bogus.image’ );

imagewbmp ( $img );
imagedestroy ( $img );
?>

User Contributed Notes 4 notes

.bmp is just hex encoded RGB values.
All you need to do is open in binary mode and seperate the header from the body.
Decode the width and height from the header.
Then create the image pixel by pixel from the RGB values in the body.

function imagecreatefrombmp( $filename )
<
$file = fopen( $filename, «rb» );
$read = fread( $file, 10 );
while( !feof( $file ) && $read != «» )
<
$read .= fread( $file, 1024 );
>
$temp = unpack( «H*», $read );
$hex = $temp[1];
$header = substr( $hex, 0, 104 );
$body = str_split( substr( $hex, 108 ), 6 );
if( substr( $header, 0, 4 ) == «424d» )
<
$header = substr( $header, 4 );
// Remove some stuff?
$header = substr( $header, 32 );
// Get the width
$w > // Remove some stuff?
$header = substr( $header, 8 );
// Get the height
$height = hexdec( substr( $header, 0, 2 ) );
unset( $header );
>
$x = 0;
$y = 1;
$image = imagecreatetruecolor( $width, $height );
foreach( $body as $rgb )
<
$r = hexdec( substr( $rgb, 4, 2 ) );
$g = hexdec( substr( $rgb, 2, 2 ) );
$b = hexdec( substr( $rgb, 0, 2 ) );
$color = imagecolorallocate( $image, $r, $g, $b );
imagesetpixel( $image, $x, $height-$y, $color );
$x++;
if( $x >= $width )
<
$x = 0;
$y++;
>
>
return $image;
>

AeroX created a nice example, but it only works at specific imagesizes because bmp uses fully 32-bit lines. To prevent failures (different colors, pixel-shifting per line), the solution is to skip the padding, inserted after color-pixels on the line. His implementation did cutting the padding into the image-data, causing wrong colors, pixel-shifting per line and also an large memory-consumption.

I improved this script to the next implementation. The readability of a image is checked by a other function, so it doesn’t take part in this script.
Suggestions? Please let me know.

public function imagecreatefrombmp ( $p_sFile )
<
// Load the image into a string
$file = fopen ( $p_sFile , «rb» );
$read = fread ( $file , 10 );
while(! feof ( $file )&&( $read <> «» ))
$read .= fread ( $file , 1024 );

$temp = unpack ( «H*» , $read );
$hex = $temp [ 1 ];
$header = substr ( $hex , 0 , 108 );

// Process the header
// Structure: http://www.fastgraph.com/help/bmp_header_format.html
if ( substr ( $header , 0 , 4 )== «424d» )
<
// Cut it in parts of 2 bytes
$header_parts = str_split ( $header , 2 );

// Get the width 4 bytes
$width = hexdec ( $header_parts [ 19 ]. $header_parts [ 18 ]);

// Get the height 4 bytes
$height = hexdec ( $header_parts [ 23 ]. $header_parts [ 22 ]);

// Unset the header params
unset( $header_parts );
>

// Define starting X and Y
$x = 0 ;
$y = 1 ;

// Create newimage
$image = imagecreatetruecolor ( $width , $height );

// Grab the body from the image
$body = substr ( $hex , 108 );

// Calculate if padding at the end-line is needed
// Divided by two to keep overview.
// 1 byte = 2 HEX-chars
$body_size = ( strlen ( $body )/ 2 );
$header_size = ( $width * $height );

// Use end-line padding? Only when needed
$usePadding = ( $body_size >( $header_size * 3 )+ 4 );

// Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
// Calculate the next DWORD-position in the body
for ( $i = 0 ; $i $body_size ; $i += 3 )
<
// Calculate line-ending and padding
if ( $x >= $width )
<
// If padding needed, ignore image-padding
// Shift i to the ending of the current 32-bit-block
if ( $usePadding )
$i += $width % 4 ;

// Reset horizontal position
$x = 0 ;

// Raise the height-position (bottom-up)
$y ++;

// Reached the image-height? Break the for-loop
if ( $y > $height )
break;
>

// Calculation of the RGB-pixel (defined as BGR in image-data)
// Define $i_pos as absolute position in the body
$i_pos = $i * 2 ;
$r = hexdec ( $body [ $i_pos + 4 ]. $body [ $i_pos + 5 ]);
$g = hexdec ( $body [ $i_pos + 2 ]. $body [ $i_pos + 3 ]);
$b = hexdec ( $body [ $i_pos ]. $body [ $i_pos + 1 ]);

// Calculate and draw the pixel
$color = imagecolorallocate ( $image , $r , $g , $b );
imagesetpixel ( $image , $x , $height — $y , $color );

// Raise the horizontal position
$x ++;
>

// Unset the body / free the memory
unset( $body );

// Return image-object
return $image ;
>
?>

Что такое код imagecreatefromwbmp

(PHP 3>= 3.0.16, PHP 4 )

imagecreatefromjpeg — Create a new image from file or URL

Description resource imagecreatefromjpeg ( string filename)

imagecreatefromjpeg() returns an image identifier representing the image obtained from the given filename.

imagecreatefromjpeg() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error JPEG :

Example 1. Example to handle an error during creation (courtesy vic at zymsys dot com )

Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function, even if allow_url_fopen is enabled.

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

// this may help to fix the error
function check_jpeg($f, $fix=false ) <
# [070203]
# check for jpeg file header and footer — also try to fix it
if ( false !== (@$fd = fopen($f, ‘r+b’ )) ) <
if ( fread($fd,2)==chr(255).chr(216) ) <
fseek ( $fd, -2, SEEK_END );
if ( fread($fd,2)==chr(255).chr(217) ) <
fclose($fd);
return true;
>else <
if ( $fix && fwrite($fd,chr(255).chr(217)) )
fclose($fd);
return false;
>
>else
>else <
return false;
>
>

Here’s the answer for your 256 color only problem.
use these functions in order then it works fine!

$img_src=imagecreatefromjpeg(‘yoursource.jpg’);
$img_dst=imagecreatetruecolor(20,20);
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, 20, 20, 20, 20);
imagejpeg($img_dst, $g_dstfile, 100);
imagedestroy($img_dst);

For Windows users who wants to enable the GD libary:

It took me some while to figure this out, but in the end it worked (and still does) great.

1. First download the latest (stable recommended) version of php
2. Unzip to f.ex c:\php\

3. Now you should have a file in c:\php\ that’s named php.ini.dist (or something like that). Rename that to php.ini and copy it to the root of you Windows directory.

4. Open the php.ini file (the easiers way is to open the run promnt at your start menu and just type php.ini and hit enter).

5. Search (ctrl+f) for extension_dir. The default value is set to «./», make it to «./extensions»

6. Now you need to find where in the php.ini the modules for Windows is located. Search for gd.

7. Remove the ; char infront of this line: extension=php_gd2.dll

8. Try make a php script with some image functions and see if it works. F.ex $im = imageCreate(«test.jpg»);
If you get a message that says something like imageCreate function doesn’t exist the gd libary is not loaded.

9. That’s all. Have fun using GD in Windows :)

As jpsy sugested Windows users can download the zip to get the gd2_dll extension

If you already installed with the windows installer and are too lazy to get the zip you can go here

Download the php_gd2.dll file put it wherever you want, and change the

Wherever you saved the dll to is the path you put in, remember to uncomment

Do not uncomment the one above for gd.dll (the one without the 2)

The following code prints out 0 on PHP4.0.6/GD1.6.2+:

$img = imagecreatefromjpeg($filename);
echo imagecolorstotal($img);
imagedestroy($img);

On PHP4.1.2/GD1.8.2 it prints out 256.

It seems that imagecreatefromjpeg() convert the image to 256 colors on the latter config.

Want to make this work under Windows and wonder how to compile the gd lib into an already existing binary?
You don’t have to. Just do it like this:

Download the Windows ZIP package from http://www.php.net/downloads.php
(You MUST use the ZIP package because the installer version does not contain any extensions. If you already installed using the installer version than thats just fine — download the ZIP nevertheless and continue below.)

Unzip the package to a temporary directory and copy the file extension\php_gd2.dll from there to your PHP folder (C:\PHP).

Open PHP.INI in your Windows directory, find this line:
;;;;;;;;;;;;;;;;;;;;;;
; Dynamic Extensions ;
;;;;;;;;;;;;;;;;;;;;;;

Below that find this line:
;extension=php_gd2.dll
. and uncomment it by removing the ;

That’s it! Isn’t it fun to be a Windowsy while others have to compile?! ;)

Note for PHP 4.3 under Mac OS X 10.2.3:

I originally compiled using only —with-mysql —with-apxs. When this compiled correctly (for a change; previous versions didn’t), I then tried adding —with-gd —with-jpg-dir and a bunch of other goodies, but they didn’t add in. Apparently removing config.cache isn’t sufficient. My advice is to simply delete the entire folder, and try your new configure command on a clean untarred source folder.

###— imagecreatefromjpeg only opens JPEG files from your disk.
###— To load JPEG images from a URL, use the function below.

function LoadJPEG ($imgURL) <

##— Get Image file from Port 80 —##
$fp = fopen($imgURL, «r»);
$imageFile = fread ($fp, 3000000);
fclose($fp);

##— Create a temporary file on disk —##
$tmpfname = tempnam («/temp», «IMG»);

##— Put image data into the temp file —##
$fp = fopen($tmpfname, «w»);
fwrite($fp, $imageFile);
fclose($fp);

##— Load Image from Disk with GD library —##
$im = imagecreatefromjpeg ($tmpfname);

##— Delete Temporary File —##
unlink($tmpfname);

##— Check for errors —##
if (!$im) <
print «Could not create JPEG image $imgURL»;
>

Header( «Content-Type: image/jpeg»);

[Ed Note: You must have netpbm installed for this to work —alindeman @ php.net]

Just wanted to let you know that
imagecreatefromjpeg crashes php
(command line at least) sometimes with segmentation fault when jpeg is corrupted.
To get rid of the nasty segmentation fault i used
system («jpegtopnm f.jpg > f.pnm», $r);
if ($r != 0) system («pnmtopng f.pnm > f.png»);
$im =imagecreatefrompng («f.png»);

Wow, it only took me 3 hours to get all of the lib paths correct for my install. Some of them are /usr, and some are /usr/lib. go figure. I figured that I would post this in the hopes that it will save somebody some time.

Remember that if you’re using rpm installs. you have to install the devel packages. For example, if you’re installing mysql from rpm, and you want to compile with support for your particular MySql dist, you must install mysql-devel*.rpm.

Anyway, I’m a redhat 7.1 install. with all appropriate devel packages installed.

./configure \
—with-mysql=/usr \
—with-ftp \
—with-apxs=/home/www/bin/apxs \
—with-xpm-dir=/usr/X11R6 \
—with-gdbm=/usr/lib \
—with-gd=/usr \
—with-zlib-dir=/usr/lib \
—with-jpeg-dir=/usr/lib \
—with-png-dir=/usr/lib \
—with-tiff-dir=/usr/lib \
—with-config-file-path=/home/www/conf \
—with-freetype-dir=/usr/lib \
—enable-magic-quotes \
—enable-track-vars

In the new versions (PHP 4.0.6, GD 2.0.1), ImageCreateFromJPEG() results in a TRUE COLOR image.

In the older versions, you only get 256 colors.

I just wanted to note here something i found else where that was very helpful to me when using jpeg images. when using imagecreatefromjpeg() it can be difficult to allocate new colors.

The work around i found was posted under imagecolorallocate() and prescribes that you first use imagecreate(), allocate colors, and then copy the jpeg into this image.

In response to my own post:

Maybe this is common knowledge but here is how I solved my problem. Hopefully this will help out seeing how I couldn’t find any other articles on this topic with a solution.

This seems to work pretty well. Displays in browser and QT Picture Viewer but for some reason Photoshop won’t open it. Translation error. Since I’m just using it to cache the image for when the our content provider goes down no biggie there.

$si = fopen($imagePathURL, «r»); // open URL

$serverImg = fread($si, 1000000); // read contents

fclose($si); // close file

/* open file to save to (w+ creates if file does not exist || b opens binary safe [Win32]) Seemed to work fine with out the ‘b’ on Windows NT but just to be safe. */

$si = fopen($saveImgTo, «w+b»);

fwrite($si, $serverImg); // write contents to file

fclose($si); // close file

Hope this helps somebody. long live PHP

To all those having trouble with a message to the effect of:

CreateImageFromJpeg() not supported in this PHP build

Start by adding —with-jpeg-dir to your ./configure options as I left this out (not knowing I needed it) and I spent the best part of 6 hours trying to compile to get this option. (RH 6.2, PHP 4.0.1pl2, Apache 1.3.12, GD 1.8.3)

Что такое код imagecreatefromwbmp

(PHP 4 >= 4.0.1, PHP 5)

imagecreatefromwbmp — Create a new image from file or URL

Description resource imagecreatefromwbmp ( string filename )

imagecreatefromwbmp() returns an image identifier representing the image obtained from the given filename.

imagecreatefromwbmp() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error WBMP :

Warning

Example 1. Example to handle an error during creation (courtesy vic at zymsys dot com)

function LoadWBMP ( $imgname )
<
$im = @ imagecreatefromwbmp ( $imgname ); /* Attempt to open */
if (! $im ) < /* See if it failed */
$im = imagecreate ( 20 , 20 ); /* Create a blank image */
$bgc = imagecolorallocate ( $im , 255 , 255 , 255 );
$tc = imagecolorallocate ( $im , 0 , 0 , 0 );
imagefilledrectangle ( $im , 0 , 0 , 10 , 10 , $bgc );
/* Output an errmsg */
imagestring ( $im , 1 , 5 , 5 , «Error loading $imgname» , $tc );
>
return $im ;
>
?>

Note: WBMP support is only available if PHP was compiled against GD-1.8 or later.

Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function, even if allow_url_fopen is enabled.

Что такое код imagecreatefromwbmp

imagecreatefromwbmp — Create a new image from file or URL

Description resource imagecreatefromwbmp ( string filename)

imagecreatefromwbmp() returns an image identifier representing the image obtained from the given filename.

imagecreatefromwbmp() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error WBMP :

Warning

Example 1. Example to handle an error during creation (courtesy vic@zymsys.com)

Note: WBMP support is only available if PHP was compiled against GD-1.8 or later.

imagecreatefromwbmp

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

imagecreatefromwbmp — Create a new image from file or URL

Description

imagecreatefromwbmp() 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 WBMP image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

Examples

Example #1 Example to handle an error during loading of a WBMP

function LoadWBMP ( $imgname )
<
/* Attempt to open */
$im = @ imagecreatefromwbmp ( $imgname );

/* See if it failed */
if(! $im )
<
/* Create a blank image */
$im = imagecreatetruecolor ( 150 , 30 );
$bgc = imagecolorallocate ( $im , 255 , 255 , 255 );
$tc = imagecolorallocate ( $im , 0 , 0 , 0 );

imagefilledrectangle ( $im , 0 , 0 , 150 , 30 , $bgc );

/* Output an error message */
imagestring ( $im , 1 , 5 , 5 , ‘Error loading ‘ . $imgname , $tc );
>

header ( ‘Content-Type: image/vnd.wap.wbmp’ );

$img = LoadWBMP ( ‘bogus.image’ );

imagewbmp ( $img );
imagedestroy ( $img );
?>

Notes

Note: WBMP support is only available if PHP was compiled against GD-1.8 or later.

User Contributed Notes

.bmp is just hex encoded RGB values.
All you need to do is open in binary mode and seperate the header from the body.
Decode the width and height from the header.
Then create the image pixel by pixel from the RGB values in the body.

function imagecreatefrombmp( $filename )
<
$file = fopen( $filename, «rb» );
$read = fread( $file, 10 );
while( !feof( $file ) && $read != «» )
<
$read .= fread( $file, 1024 );
>
$temp = unpack( «H*», $read );
$hex = $temp[1];
$header = substr( $hex, 0, 104 );
$body = str_split( substr( $hex, 108 ), 6 );
if( substr( $header, 0, 4 ) == «424d» )
<
$header = substr( $header, 4 );
// Remove some stuff?
$header = substr( $header, 32 );
// Get the width
$w > // Remove some stuff?
$header = substr( $header, 8 );
// Get the height
$height = hexdec( substr( $header, 0, 2 ) );
unset( $header );
>
$x = 0;
$y = 1;
$image = imagecreatetruecolor( $width, $height );
foreach( $body as $rgb )
<
$r = hexdec( substr( $rgb, 4, 2 ) );
$g = hexdec( substr( $rgb, 2, 2 ) );
$b = hexdec( substr( $rgb, 0, 2 ) );
$color = imagecolorallocate( $image, $r, $g, $b );
imagesetpixel( $image, $x, $height-$y, $color );
$x++;
if( $x >= $width )
<
$x = 0;
$y++;
>
>
return $image;
>

AeroX created a nice example, but it only works at specific imagesizes because bmp uses fully 32-bit lines. To prevent failures (different colors, pixel-shifting per line), the solution is to skip the padding, inserted after color-pixels on the line. His implementation did cutting the padding into the image-data, causing wrong colors, pixel-shifting per line and also an large memory-consumption.

I improved this script to the next implementation. The readability of a image is checked by a other function, so it doesn’t take part in this script.
Suggestions? Please let me know.

public function imagecreatefrombmp ( $p_sFile )
<
// Load the image into a string
$file = fopen ( $p_sFile , «rb» );
$read = fread ( $file , 10 );
while(! feof ( $file )&&( $read <> «» ))
$read .= fread ( $file , 1024 );

$temp = unpack ( «H*» , $read );
$hex = $temp [ 1 ];
$header = substr ( $hex , 0 , 108 );

// Process the header
// Structure: http://www.fastgraph.com/help/bmp_header_format.html
if ( substr ( $header , 0 , 4 )== «424d» )
<
// Cut it in parts of 2 bytes
$header_parts = str_split ( $header , 2 );

// Get the width 4 bytes
$width = hexdec ( $header_parts [ 19 ]. $header_parts [ 18 ]);

// Get the height 4 bytes
$height = hexdec ( $header_parts [ 23 ]. $header_parts [ 22 ]);

// Unset the header params
unset( $header_parts );
>

// Define starting X and Y
$x = 0 ;
$y = 1 ;

// Create newimage
$image = imagecreatetruecolor ( $width , $height );

// Grab the body from the image
$body = substr ( $hex , 108 );

// Calculate if padding at the end-line is needed
// Divided by two to keep overview.
// 1 byte = 2 HEX-chars
$body_size = ( strlen ( $body )/ 2 );
$header_size = ( $width * $height );

// Use end-line padding? Only when needed
$usePadding = ( $body_size >( $header_size * 3 )+ 4 );

// Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
// Calculate the next DWORD-position in the body
for ( $i = 0 ; $i $body_size ; $i += 3 )
<
// Calculate line-ending and padding
if ( $x >= $width )
<
// If padding needed, ignore image-padding
// Shift i to the ending of the current 32-bit-block
if ( $usePadding )
$i += $width % 4 ;

// Reset horizontal position
$x = 0 ;

// Raise the height-position (bottom-up)
$y ++;

// Reached the image-height? Break the for-loop
if ( $y > $height )
break;
>

// Calculation of the RGB-pixel (defined as BGR in image-data)
// Define $i_pos as absolute position in the body
$i_pos = $i * 2 ;
$r = hexdec ( $body [ $i_pos + 4 ]. $body [ $i_pos + 5 ]);
$g = hexdec ( $body [ $i_pos + 2 ]. $body [ $i_pos + 3 ]);
$b = hexdec ( $body [ $i_pos ]. $body [ $i_pos + 1 ]);

// Calculate and draw the pixel
$color = imagecolorallocate ( $image , $r , $g , $b );
imagesetpixel ( $image , $x , $height — $y , $color );

// Raise the horizontal position
$x ++;
>

// Unset the body / free the memory
unset( $body );

// Return image-object
return $image ;
>
?>

To get the horizontal and vertical resolution you could add some lines to the previous code of alexander. BMP stores the resolution in pixels per meter. To get it as pixels per inch (dpi) you have to multiply the value by 0.0254.

public function imagecreatefrombmp ( $p_sFile )
<
// .
// . insert after the lines where you get width and height.

// Get the horz. resolution in pixel per meter, 4 bytes
$dpix = hexdec ( $header_parts [ 39 ]. $header_parts [ 38 ]) * 0.0254 ;

// Get the vert. resolution in pixel per meter, 4 bytes
$dpiy = hexdec ( $header_parts [ 43 ]. $header_parts [ 42 ]) * 0.0254 ;

// . rest of the code.

return ( $image , $dpix , $dpiy );
>
?>

Илон Маск рекомендует:  Что такое код loadresource
Понравилась статья? Поделиться с друзьями:
Кодинг, CSS и SQL