Php создать jpg файл

imagejpeg

Функция imagejpeg() создаёт файл JPEG из изображения image .

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

Ресурс изображения, полученный одной из функций создания изображений, например, такой как imagecreatetruecolor() .

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

Если вы хотите пропустить этот параметр и использовать quality , то укажите NULL .

Необязательный параметр, и может принимать значения в диапазоне от 0 (низкое качество, маленький размер файла) до 100 (высокое качество, большой размер файла). По умолчанию используется качество IJG (около 75).

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

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

Примеры

Пример #1 Вывод JPEG-изображения

// Создаём пустое изображение и добавляем текст
$im = imagecreatetruecolor ( 120 , 20 );
$text_color = imagecolorallocate ( $im , 233 , 14 , 91 );
imagestring ( $im , 1 , 5 , 5 , ‘A Simple Text String’ , $text_color );

// Устанавливаем тип содержимого в заголовок, в данном случае image/jpeg
header ( ‘Content-Type: image/jpeg’ );

// Выводим изображение
imagejpeg ( $im );

// Освобождаем память
imagedestroy ( $im );
?>

Результатом выполнения данного примера будет что-то подобное:

Пример #2 Сохранение изображения JPEG

// Создаём пустое изображение и добавляем текст
$im = imagecreatetruecolor ( 120 , 20 );
$text_color = imagecolorallocate ( $im , 233 , 14 , 91 );
imagestring ( $im , 1 , 5 , 5 , ‘A Simple Text String’ , $text_color );

// Сохраняем изображение в ‘simpletext.jpg’
imagejpeg ( $im , ‘simpletext.jpg’ );

// Освобождаем память
imagedestroy ( $im );
?>

Пример #3 Вывод JPEG-изображения с 75% качеством

// Создаём пустое изображение и добавляем текст
$im = imagecreatetruecolor ( 120 , 20 );
$text_color = imagecolorallocate ( $im , 233 , 14 , 91 );
imagestring ( $im , 1 , 5 , 5 , ‘A Simple Text String’ , $text_color );

// Устанавливаем тип содержимого в заголовок, в данном случае image/jpeg
header ( ‘Content-Type: image/jpeg’ );

// Пропускаем параметр filename, используя NULL, а затем устанавливаем качество в 75%
imagejpeg ( $im , NULL , 75 );

// Освобождаем память
imagedestroy ( $im );
?>

Примечания

Замечание: Поддержка JPEG доступна только в случае, если PHP был скомпилирован с GD-1.8 или более поздней версии.

Замечание:

Если требуется вывести Progressive JPEG (прогрессивное представление данных), то необходимо использовать функцию imageinterlace() для активации соответствующего режима.

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

  • imagepng() — Вывод PNG изображения в броузер или файл
  • imagegif() — Выводит изображение в браузер или пишет в файл
  • imagewbmp() — Выводит изображение в браузер или пишет в файл
  • imageinterlace() — Включение или выключение интерлейсинга
  • imagetypes() — Возвращает список типов изображений, поддерживаемых PHP сборкой

Источник

imagecreatefromjpeg

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

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

Читайте также:  Java set memory size

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

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

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

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

Версия Описание
8.0.0 В случае успешного выполнения функция теперь возвращает экземпляр GDImage ; ранее возвращался ресурс ( resource ).

Примеры

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

function LoadJpeg ( $imgname )
/* Пытаемся открыть */
$im = @ imagecreatefromjpeg ( $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/jpeg’ );

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

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

Результатом выполнения данного примера будет что-то подобное:

Вывод примера: Пример обработки ошибки при загрузке JPEG

User Contributed Notes 34 notes

This little function allows you to create an image based on the popular image types without worrying about what it is:

function imageCreateFromAny ( $filepath ) <
$type = exif_imagetype ( $filepath ); // [] if you don’t have exif you could use getImageSize()
$allowedTypes = array(
1 , // [] gif
2 , // [] jpg
3 , // [] png
6 // [] bmp
);
if (! in_array ( $type , $allowedTypes )) <
return false ;
>
switch ( $type ) <
case 1 :
$im = imageCreateFromGif ( $filepath );
break;
case 2 :
$im = imageCreateFromJpeg ( $filepath );
break;
case 3 :
$im = imageCreateFromPng ( $filepath );
break;
case 6 :
$im = imageCreateFromBmp ( $filepath );
break;
>
return $im ;
>
?>

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.

function imagecreatefromjpegexif ( $filename )
$img = imagecreatefromjpeg ( $filename );
$exif = exif_read_data ( $filename );
if ( $img && $exif && isset( $exif [ ‘Orientation’ ]))
$ort = $exif [ ‘Orientation’ ];

if ( $ort == 6 || $ort == 5 )
$img = imagerotate ( $img , 270 , null );
if ( $ort == 3 || $ort == 4 )
$img = imagerotate ( $img , 180 , null );
if ( $ort == 8 || $ort == 7 )
$img = imagerotate ( $img , 90 , null );

if ( $ort == 5 || $ort == 4 || $ort == 7 )
imageflip ( $img , IMG_FLIP_HORIZONTAL );
>
return $img ;
>
?>

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-

.
$image = @ ImageCreateFromJpeg ( $image_name );
if (! $image )
$image = imagecreatefromstring ( file_get_contents ( $image_name ));
>
.
?>

In PHP 8, you can create an image based on the popular image types without worrying about what it is:

function imageCreateFromAny ( $filepath ): ?\ GdImage return match ( exif_imagetype ( $filepath )) // gif
1 => imageCreateFromGif ( $filepath ),
// jpg
2 => imageCreateFromJpeg ( $filepath ),
// png
3 => imageCreateFromPng ( $filepath ),
// bmp
6 => imageCreateFromBmp ( $filepath ),
// not defined
default => null ,
>;
>
?>

Читайте также:  Java изменение формата даты

If imagecreatefromjpeg() fails with «PHP Fatal error: Call to undefined function: imagecreatefromjpeg()», it does NOT necessarily mean that you don’t have GD installed.

If phpinfo() shows GD, but not JPEG support, then that’s the problem. You would think that —with-gd would do the right thing since it does check for the existance of libjpeg (and finds it) and add that feature to GD, but it doesn’t in v4.4.4 at least on RHEL v2.1, RHEL v3, CentOS v2.1 or CentOS v4.3.

On those platforms, it’s *important* that —with-jpeg-dir be *before* —with-gd. If it’s not, GD won’t build with jpeg support as if —with-jpeg-dir had never been specified.

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;
>
>

When working with uploaded jpeg files it is usually a good idea to execute a little but very useful program called jhead
( http://www.sentex.net/~mwandel/jhead/ ).

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.

Usage:
exec ( «/path/to/jhead -purejpg /path/to/image» );
// for example when you uploaded a file through a form, do this before you proceed:
exec ( «/path/to/jhead -purejpg » . $file [ ‘tmp_name’ ]);
?>

I didn’t have the chance to test this but I guess this might even solve the problem caused by images that were taken with Canon PowerShot cameras which crash PHP.

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.

Читайте также:  Css страница шире экрана

— from move_upload_file post —

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.

1. adjust server memory size, file upload size, and post size
2. convert image to standard formate (in this case jpg) and scale

The server may be adjusted with the .htaccess file or inline code. This example has an .htaccess file with file upload size and post size and then inline code for dynamic system memory.

htaccess file:
php_value post_max_size 16M
php_value upload_max_filesize 6M

// $img_base = base directory structure for thumbnail images
// $w_dst = maximum width of thumbnail
// $h_dst = maximum height of thumbnail
// $n_img = new thumbnail name
// $o_img = old thumbnail name
function convertPic ( $img_base , $w_dst , $h_dst , $n_img , $o_img )
< ini_set ( 'memory_limit' , '100M' ); // handle large images
unlink ( $img_base . $n_img ); // remove old images if present
unlink ( $img_base . $o_img );
$new_img = $img_base . $n_img ;

$file_src = $img_base . «img.jpg» ; // temporary safe image storage
unlink ( $file_src );
move_uploaded_file ( $_FILES [ ‘Filedata’ ][ ‘tmp_name’ ], $file_src );

list( $w_src , $h_src , $type ) = getimagesize ( $file_src ); // create new dimensions, keeping aspect ratio
$ratio = $w_src / $h_src ;
if ( $w_dst / $h_dst > $ratio ) < $w_dst = floor ( $h_dst * $ratio );>else < $h_dst = floor ( $w_dst / $ratio );>

switch ( $type )
jpg
$img_src = imagecreatefromgif ( $file_src );
break;
case 2 : // jpeg -> jpg
$img_src = imagecreatefromjpeg ( $file_src );
break;
case 3 : // png -> jpg
$img_src = imagecreatefrompng ( $file_src );
break;
>
$img_dst = imagecreatetruecolor ( $w_dst , $h_dst ); // resample

imagecopyresampled ( $img_dst , $img_src , 0 , 0 , 0 , 0 , $w_dst , $h_dst , $w_src , $h_src );
imagejpeg ( $img_dst , $new_img ); // save new image

unlink ( $file_src ); // clean up image storage
imagedestroy ( $img_src );
imagedestroy ( $img_dst );
>

$p_id = (Integer) $_POST [ uid ];
$ver = (Integer) $_POST [ ver ];
$delver = (Integer) $_POST [ delver ];
convertPic ( «your/file/structure/» , 150 , 150 , «u» . $p_id . «v» . $ver . «.jpg» , «u» . $p_id . «v» . $delver . «.jpg» );

Источник

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