Open jpg file in php

imagepng

Объект GdImage , возвращаемый одной из функций создания изображений, например, такой как imagecreatetruecolor() .

Путь, или открытый потоковый ресурс (который автоматически закрывается после завершения функции), для сохранения файла. Если не установлен или равен null , изображение будет выведено в поток вывода в бинарном виде.

Замечание:

Недопустимо передавать null , если не используются аргументы quality и filters .

Степень сжатия: от 0 (нет сжатия) до 9. По умолчанию ( -1 ) используется значение по умолчанию сжатия zlib. Более подробно читайте в » руководстве по zlib.

Позволяет уменьшить размер PNG файла. Это битовая маска, значением которой может быть комбинация констант PNG_FILTER_XXX . Для включения или выключения всех фильтров удобно воспользоваться константами PNG_NO_FILTER или PNG_ALL_FILTERS соответственно. Значение по умолчанию ( -1 ) отключает фильтрацию.

Параметр filters игнорируется системной библиотекой libgd.

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

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Однако, если libgd не может вывести изображения, эта функция вернёт true .

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

Версия Описание
8.0.0 image теперь ожидает экземпляр GdImage ; ранее ожидался корректный gd ресурс ( resource ).

Примеры

$im = imagecreatefrompng ( «test.png» );

header ( ‘Content-Type: image/png’ );

imagepng ( $im );
imagedestroy ( $im );
?>

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

  • imagegif() — Выводит изображение в браузер или пишет в файл
  • imagewbmp() — Выводит изображение в браузер или пишет в файл
  • imagejpeg() — Выводит изображение в браузер или пишет в файл
  • imagetypes() — Возвращает список типов изображений, поддерживаемых PHP сборкой
  • imagesavealpha() — Сохранять ли полную информацию альфа-канала при сохранении изображений

User Contributed Notes 35 notes

The name «quality» for the compression parameter is quite misleading, as png compression is always lossless. The trade off is between speed and filesize, it cannot affect quality.

Here’s something I found at stackoverflow; I haven’t checked it, but if it is correct it should definitely included in the documentation:

/* 2.0.12: Compression level: 0-9 or -1, where 0 is NO COMPRESSION at all,
* 1 is FASTEST but produces larger files, 9 provides the best
* compression (smallest files) but takes a long time to compress, and
* -1 selects the default compiled into the zlib library.
*/
Conclusion: Based on the Zlib manual (http://www.zlib.net/manual.html) the default compression level is set to 6.

Regarding suggestions to rescale the 0-99 quality range of jpeg into the 0-9 range of png, note that for jpeg 99 is minimum compression (maximum quality) while for png 9 is maximum compression (quality doesn’t change).

«Tip: As with anything that outputs its result directly to the browser, you can use the output-control functions (http://www.php.net/manual/en/ref.outcontrol.php) to capture the output of this function, and save it in a string (for example).»

And now you can save $image_data to a database, for example, instead of first writing it to file and then reading the data from it. Just don’t forget to use mysql_escape_string.

to all the ones, who like having their users fill their profil with an image without destroying a fixed design the following should be a great way to handle this problem.

Читайте также:  Php read url https

this file opens a picture from $imagepath and returns it as a valid picture to embed in: (in [] = optional)

but this file does more than this. it also adds black borders to files that are smaller than the max. size, so adding borders to the left and right where a image is too high 🙂

if there is a need for a copyright note this script will also help you. you can put in a various text to $copyright. the text length should be in relationship to $maxX and $maxY.

Well there are other features of the script, just try’em out and have fun with it 🙂

# colour- & textvalues
$picBG = «0,0,0» ; # RGB-value !
$picFG = «104,104,104» ; # RGB-value !
$copyright = «stefan bechtold» ;
$font = 1 ;

# minimal & maximum zoom
$minZoom = 1 ; # per cent related on orginal (!=0)
$maxZoom = 200 ; # per cent related on orginal (!=0)

# paths
$imgpath = «userimages/» ; # ending with «/» !
$nopicurl = «../images/nopic.jpg» ; # starting in $imagepath.
$nofileurl = «../images/nofile.jpg» ; # starting in $imagepath.

if(!isset( $image ) || empty( $image ))
$imageurl = $imgpath . $nopicurl ;
elseif(! file_exists ( $imgpath . trim ( $image )))
$imageurl = $imgpath . $nofileurl ;
else
$imageurl = $imgpath . trim ( $image );

# reading image
$image = getImageSize ( $imageurl , $info ); # $info, only to handle problems with earlier php versions.
switch( $image [ 2 ]) case 1 :
# GIF image
$timg = imageCreateFromGIF ( $imageurl );
break;
case 2 :
# JPEG image
$timg = imageCreateFromJPEG ( $imageurl );
break;
case 3 :
# PNG image
$timg = imageCreateFromPNG ( $imageurl );
break;
>

# reading image sizes
$imgX = $image [ 0 ];
$imgY = $image [ 1 ];

# calculation zoom factor
$_X = $imgX / $maxX * 100 ;
$_Y = $imgY / $maxY * 100 ;

# selecting correct zoom factor, so that the image always keeps in the given format
# no matter if it is more higher than wider or the other way around
if(( 100 — $_X ) < ( 100 - $_Y )) $_K = $_X ;
else $_K = $_Y ;

# zoom check to the original
if( $_K > 10000 / $minZoom ) $_K = 10000 / $minZoom ;
if( $_K < 10000 / $maxZoom ) $_K = 10000 / $maxZoom ;

# calculate new image sizes
$newX = $imgX / $_K * 100 ;
$newY = $imgY / $_K * 100 ;

# set start positoin of the image
# always centered
$posX = ( $maxX — $newX ) / 2 ;
$posY = ( $maxY — $newY ) / 2 ;

# creating new image with given sizes
$imgh = imageCreateTrueColor ( $maxX , $maxY );

# setting colours
$cols = explode ( «,» , $picBG );
$bgcol = imageColorallocate ( $imgh , trim ( $cols [ 0 ]), trim ( $cols [ 1 ]), trim ( $cols [ 2 ]));
$cols = explode ( «,» , $picFG );
$fgcol = imageColorallocate ( $imgh , trim ( $cols [ 0 ]), trim ( $cols [ 1 ]), trim ( $cols [ 2 ]));

# fill background
imageFill ( $imgh , 0 , 0 , $bgcol );

# create small copy of the image
imageCopyResampled ( $imgh , $timg , $posX , $posY , 0 , 0 , $newX , $newY , $image [ 0 ], $image [ 1 ]);

# writing copyright note
imageStringUp ( $imgh , $font , $maxX — 9 , $maxY — 3 , $copyright , $fgcol );

# output
switch( $image [ 2 ]) case 1 :
# GIF image
header ( «Content-type: image/gif» );
imageGIF ( $imgh );
case 2 :
# JPEG image
header ( «Content-type: image/jpeg» );
imageJPEG ( $imgh );
case 3 :
# PNG image
header ( «Content-type: image/png» );
imagePNG ( $imgh );
>

# cleaning cache
imageDestroy ( $timg );
imageDestroy ( $imgh );

Читайте также:  Get text from pdf java

I just lost about 4 hours on a really stupid problem. My images on the local server were somehow broken and therefore did not display in the browsers. After much looking around and testing, including re-installing apache on my computer a couple of times, I traced the problem to an included file.
No the problem was not a whitespace, but the UTF BOM encoding character at the begining of one of my inluded files.
So beware of your included files!
Make sure they are not encoded in UTF or otherwise in UTF without BOM.
Hope it save someone’s time.

If you want to open a png image with alpha blending, you need to do something like this:

$file = ‘semitransparent.png’ ; // path to png image
$img = imagecreatefrompng ( $file ); // open image
imagealphablending ( $img , true ); // setting alpha blending on
imagesavealpha ( $img , true ); // save alphablending setting (important)
?>

I spent almost a day to find out why alpha blending doesn’t work. I hope this is usefull to others too 🙂

Be careful when using a variable for the file name.
PHP behavior with $filename differs when switching to PHP5.4 : PHP5.3 will use $filename=» the same way as $filename=NULL (e.g. no warning)
$im = imagecreatetruecolor ( 10 , 10 );
imagepng ( $im , » , 9 ); # Warning: imagepng(): Filename cannot be empty
imagepng ( $im , NULL , 9 ); # works as expected
imagedestroy ( $im );
?>

PNG files are already compressed. They use a lossless compression algorithm. If you are using HighColour images, the compression only does so much. For low colour images (16 or 256) the compression is much better.

It is pointless trying to compress the images further before sending to a browser.

If you’re generating an image dynamically based on post data and don’t want to save it to the server, sending it to be displayed can cause problems as when the person tries to save it, the browser will request it again from the server (causing any post data to be lost and probably a corrupted png).

The easiest way to get around this is to force it to download using the content disposition header, for example:

header ( ‘Content-Disposition: Attachment;filename=image.png’ );
header ( ‘Content-type: image/png’ );
?>

I have experienced segfaults and bus errors with the following configuration: FreeBSD4.4, Apache 1.3.26, PHP 4.2.2, GD-1.8.4, PDFlib 4.0.1. The apache process crashed when calling the imagepng function, but it didn’t crash when calling the imagejpg function, or imagecreatefrompng.

Some wasted hours (lots) later, in which I have tried to recompile gd, libpng, php, libjpeg, what-not, I have found the following advices:
http://bugs.php.net/bug.php?id=16841

So the problem was not with the png library, but rather with the PDFlib. Even though all the threads led to a png-problem. so I have simply upgraded to PDFlib 4.0.3 (w/o any special configure arguments; —with-libpng didn’t work anyways), recompiled PHP, and now everything works (imagepng, pdf creation, etc.).

Читайте также:  Кнопка наверх с помощью CSS - "Нубекс"

If you are outputting a PNG directly in response to a client request it is important to check your web server configuration.

Apache is specifically discussed at http://stackoverflow.com/q/19169337 but other server have been documented to have issue too.

In other words, when testing your application don’t just use the web browser, consider a phone’s browser and networking libraries which could send different headers.

I was curious about the relationship between quality, processing time and resulting image size, so I created this little benchmark to test it (The image used was originally RGB_24bits_palette_R85.png, found on wikipedia). Results are at the bottom.
$sizes = [ ’32’ , ’64’ , ‘128’ , ‘256’ , ‘512’ , ‘1024’ , ‘2048’ ];

foreach ( $sizes as $size ) echo «\nSize: < $size >x < $size >px:\n» ;

$image = imagecreatefrompng ( «images/test < $size >.png» );
for ( $quality = 0 ; $quality < 10 ; $quality ++) ob_start ();

$start = microtime ( true );
imagepng ( $image , null , $quality );
$elapsed = microtime ( true ) — $start ;

$blob = ob_get_contents ();
ob_end_clean ();

$blobSize = strlen ( $blob );
echo «quality: $quality , size: $blobSize , elapsed: $elapsed \n» ;
>

// Results (some omitted for brevity):

// Size: 32x32px:
// quality: 0, size: 3172, elapsed: 0.00013399124145508
// quality: 1, size: 266, elapsed: 9.4890594482422E-5
// quality: 2, size: 264, elapsed: 7.7009201049805E-5
// quality: 3, size: 223, elapsed: 7.4863433837891E-5
// quality: 4, size: 225, elapsed: 8.5830688476562E-5
// quality: 5, size: 209, elapsed: 8.5115432739258E-5
// quality: 6, size: 208, elapsed: 9.608268737793E-5
// quality: 7, size: 205, elapsed: 0.0001060962677002
// quality: 8, size: 186, elapsed: 0.00015091896057129
// quality: 9, size: 181, elapsed: 0.00022006034851074

// Size: 128x128px:
// quality: 0, size: 49425, elapsed: 0.0010969638824463
// quality: 1, size: 976, elapsed: 0.00091886520385742
// quality: 2, size: 938, elapsed: 0.00088310241699219
// quality: 3, size: 925, elapsed: 0.00087594985961914
// quality: 4, size: 608, elapsed: 0.0009760856628418
// quality: 5, size: 607, elapsed: 0.00098395347595215
// quality: 6, size: 601, elapsed: 0.0010099411010742
// quality: 7, size: 602, elapsed: 0.001086950302124
// quality: 8, size: 521, elapsed: 0.001910924911499
// quality: 9, size: 491, elapsed: 0.0029060840606689

// Size: 512x512px:
// quality: 0, size: 788279, elapsed: 0.012928009033203
// quality: 1, size: 12467, elapsed: 0.013065099716187
// quality: 2, size: 11885, elapsed: 0.013008117675781
// quality: 3, size: 11190, elapsed: 0.013030052185059
// quality: 4, size: 7311, elapsed: 0.016619920730591
// quality: 5, size: 6994, elapsed: 0.016351222991943
// quality: 6, size: 6475, elapsed: 0.016234159469604
// quality: 7, size: 6432, elapsed: 0.016525983810425
// quality: 8, size: 6094, elapsed: 0.022937774658203
// quality: 9, size: 5649, elapsed: 0.065664052963257

// Size: 2048x2048px:
// quality: 0, size: 12605375, elapsed: 0.20983290672302
// quality: 1, size: 451735, elapsed: 0.19678711891174
// quality: 2, size: 409375, elapsed: 0.19415307044983
// quality: 3, size: 366404, elapsed: 0.20460414886475
// quality: 4, size: 312538, elapsed: 0.22785305976868
// quality: 5, size: 281671, elapsed: 0.23320484161377
// quality: 6, size: 244248, elapsed: 0.28935289382935
// quality: 7, size: 238310, elapsed: 0.33481192588806
// quality: 8, size: 217038, elapsed: 0.71698379516602
// quality: 9, size: 208881, elapsed: 1.858146905899
?>

Источник

Оцените статью