Save php as jpg

imagejpeg

imagejpeg () создает JPEG файл из данного image .

Parameters

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

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

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

Return Values

Возвращает true в случае успеха или false в случае неудачи.

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

Changelog

Examples

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

 // Create a blank image and add some text $im = imagecreatetruecolor(120, 20); $text_color = imagecolorallocate($im, 233, 14, 91); imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color); // Set the content type header - in this case image/jpeg header('Content-Type: image/jpeg'); // Output the image imagejpeg($im); // Free up memory imagedestroy($im); ?>

Из приведенного выше примера будет выведено нечто подобное:

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

 // Create a blank image and add some text $im = imagecreatetruecolor(120, 20); $text_color = imagecolorallocate($im, 233, 14, 91); imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color); // Save the image as 'simpletext.jpg' imagejpeg($im, 'simpletext.jpg'); // Free up memory imagedestroy($im); ?>

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

 // Create a blank image and add some text $im = imagecreatetruecolor(120, 20); $text_color = imagecolorallocate($im, 233, 14, 91); imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color); // Set the content type header - in this case image/jpeg header('Content-Type: image/jpeg'); // Skip the to parameter using NULL, then set the quality to 75% imagejpeg($im, NULL, 75); // Free up memory imagedestroy($im); ?>

Notes

Note:

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

See Also

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

(PHP 4 4.3.2,5,7,8)imageistruecolor Выясняет,является ли объект A GdImage,возвращенный одной из функций создания,например,imagecreatetruecolor().

(PHP 4 4.3.0,5,7,8)imagelayereffect Установка флага альфа-смешивания для использования эффекта наслоения Установка флага альфа-смешивания для использования эффекта наслоения.

Источник

Convert Image Format In PHP (WEBP JPG PNG GIF)

Welcome to a tutorial on how to convert the image file format in PHP – From JPG to WEBP, from PNG to JPG, from PNG to WEBP, and whatever else.

  • Open the original image – $img = imagecreatefromjpeg(«IMG.JPG»);
  • Set the color palette – imagepalettetotruecolor($img);
  • Convert and save the image – imagewebp($img, «IMG.WEBP»);

That’s all, 3 lines of code. To convert the other file formats, simply open/save the image using their respective functions –

  • imagecreatefromjpeg() imagejpeg()
  • imagecreatefrompng() imagepng()
  • imagecreatefromgif() imagegif()
  • imagecreatefromwebp() imagewebp()
  • imagecreatefrombmp() imagebmp()

That covers the basics, but read on for more examples!

TLDR – QUICK SLIDES

Convert Image File Format In PHP

TABLE OF CONTENTS

PHP CONVERT IMAGE

The introduction covered the basics, here are a few more examples that may be useful.

1) MASS CONVERT THE ENTIRE FOLDER

"; // glob brace, image types to convert $valid = ["bmp", "jpg", "jpeg", "png", "gif", "webp"]; // (B) CONVERT IMAGE FILES TO WEBP foreach (glob("$dir$convert", GLOB_BRACE) as $file) < // (B1) CHECK VALID IMAGE $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION)); if (!in_array($ext, $valid)) < continue; >// (B2) "SAVE AS" FILE NAME $name = pathinfo($file, PATHINFO_FILENAME); $saveas = "$name.webp"; // do not override existing - remove this to override if (file_exists("$dir$saveas")) < continue; >// (B3) CONVERT IMAGE if ($ext=="jpg") < $ext = "jpeg"; >$fn = "imagecreatefrom$ext"; $img = $fn($file); imagepalettetotruecolor($img); imagewebp($img, "$dir$saveas", 70); imagedestroy($img); // unlink($file); // remove original if you want echo "$dir$saveas - OK"; >

  1. The target folder, files to convert, and the list of valid images.
  2. Extracts a list of images and convert them.
    • (B1) Some may think a “valid image check” is irrelevant, but my line of thought is – PHP GD only supports certain image types, a check against the supported images in $valid is necessary.
    • (B2) “Save as” file name. Yes, remove that file_exists() check if you want to override previously convert files.
    • (B3) As in the introduction – Open the image, save as webp .

2) UPLOAD & CONVERT

2A) HTML UPLOAD FORM

This is a simple file upload form. If you want “fancy uploads”, I will leave a few links below.

2B) PHP CONVERT UPLOADED IMAGE FILE

 // (B) MOVE UPLOADED FILE TO IMAGES FOLDER - ONLY IF VALID if (!in_array($ext, $valid)) < exit("INVALID IMAGE"); >move_uploaded_file( $_FILES["up"]["tmp_name"], $dir . $_FILES["up"]["name"] ); // (C) CONVERT IF NEEDED if ($ext != "webp") < if ($ext=="jpg") < $ext = "jpeg"; >$fn = "imagecreatefrom$ext"; $img = $fn($saveto); imagepalettetotruecolor($img); imagewebp($img, $saveas, 70); imagedestroy($img); // unlink($dir . $_FILES["up"]["name"]); // delete original if you want > // (D) WHAT'S NEXT? // REDIRECT TO ANOTHER PAGE? // SHOW AN "UPLOAD OK PAGE"? // SIMPLE MESSAGE? echo "OK";
  1. Settings – Where to save the uploaded file to, what is the uploaded file name, extension, etc…
  2. Move the uploaded file, only if it is a valid image.
  3. Convert the image if it is not webp . Pretty much the same as the introduction snippet.
  4. What to do after the conversion.

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

COMPATIBILITY CHECKS

Works on all modern “Grade A” browsers.

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Источник

Image Convert to JPG, PNG & GIF using PHP

In this post I help you to convert any uploaded image to JPG, PNG and GIF.

Create a file image_converter.php.

In this code you see using convert_image() has three mandatory parameters like as:

$convert_type => accepts string either png,jpg or gif.
$target_dir => it is the source as well as the target directory
$image_name => give the actual image name such as image1.jpg.
$image_quality => can be adjusted, if you don’t want 100% quality.

Next, create index.php to Upload the image.

Then, create convert.php to convert the image. And make a folder in your directory name as uploads. Because when the image is uploaded or convert, the image will save on this folder.

And, create a download.php to downloads the converted image forcefully.

Then, Run the index.php and see the view.

After Upload the image.

After converted the image.

Then, you can download or convert another image.

Источник

imagejpeg

imagejpeg() creates a JPEG file from the given image .

Parameters

A GdImage object, returned by one of the image creation functions, such as imagecreatetruecolor().

The path or an open stream resource (which is automatically closed after this function returns) to save the file to. If not set or null , the raw image stream will be output directly.

quality is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default ( -1 ) uses the default IJG quality value (about 75).

Return Values

Returns true on success or false on failure.

However, if libgd fails to output the image, this function returns true .

Changelog

Examples

Example #1 Outputting a JPEG image to the browser

 // Create a blank image and add some text $im = imagecreatetruecolor(120, 20); $text_color = imagecolorallocate($im, 233, 14, 91); imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color); // Set the content type header - in this case image/jpeg header('Content-Type: image/jpeg'); // Output the image imagejpeg($im); // Free up memory imagedestroy($im); ?>

The above example will output something similar to:

Example #2 Saving a JPEG image to a file

 // Create a blank image and add some text $im = imagecreatetruecolor(120, 20); $text_color = imagecolorallocate($im, 233, 14, 91); imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color); // Save the image as 'simpletext.jpg' imagejpeg($im, 'simpletext.jpg'); // Free up memory imagedestroy($im); ?>

Example #3 Outputting the image at 75% quality to the browser

 // Create a blank image and add some text $im = imagecreatetruecolor(120, 20); $text_color = imagecolorallocate($im, 233, 14, 91); imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color); // Set the content type header - in this case image/jpeg header('Content-Type: image/jpeg'); // Skip the to parameter using NULL, then set the quality to 75% imagejpeg($im, NULL, 75); // Free up memory imagedestroy($im); ?>

Notes

Note:

If you want to output Progressive JPEGs, you need to set interlacing on with imageinterlace().

See Also

  • imagepng() — Output a PNG image to either the browser or a file
  • imagegif() — Output image to browser or file
  • imagewbmp() — Output image to browser or file
  • imageinterlace() — Enable or disable interlace
  • imagetypes() — Return the image types supported by this PHP build
PHP 8.2

(PHP 4 4.3.2, 5, 7, 8) imageistruecolor Finds whether an A GdImage object, returned by one of the creation functions, such as imagecreatetruecolor().

(PHP 4 4.3.0, 5, 7, 8) imagelayereffect Set the alpha blending flag to use layering Set the alpha blending flag to use layering effects.

Источник

Читайте также:  Html button перенос строки
Оцените статью