dolibarr 25.0.0-alpha
images.lib.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2004-2010 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2005-2007 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 * or see https://www.gnu.org/
20 */
21
27// Define size of logo small and mini
28// TODO Remove this and call getDefaultImageSizes() instead
29$maxwidthsmall = 480;
30$maxheightsmall = 270; // Near 16/9eme
31$maxwidthmini = 128;
32$maxheightmini = 72; // 16/9eme
33$quality = 80;
34
35if (!defined('IMAGETYPE_WEBP')) {
36 define('IMAGETYPE_WEBP', 18);
37}
38
39
46{
47 $maxwidthsmall = 480;
48 $maxheightsmall = 270; // Near 16/9eme
49 $maxwidthmini = 128;
50 $maxheightmini = 72; // 16/9eme
51 $quality = 80;
52
53 return array(
54 'maxwidthsmall' => $maxwidthsmall,
55 'maxheightsmall' => $maxheightsmall,
56 'maxwidthmini' => $maxwidthmini,
57 'maxheightmini' => $maxheightmini,
58 'quality' => $quality
59 );
60}
61
68function getListOfPossibleImageExt($acceptsvg = 0)
69{
70 $regeximgext = '\.gif|\.jpg|\.jpeg|\.png|\.bmp|\.webp|\.xpm|\.xbm|\.avif'; // See also into product.class.php
71 if ($acceptsvg || getDolGlobalString('MAIN_ALLOW_SVG_FILES_AS_IMAGES')) {
72 $regeximgext .= '|\.svg'; // Not allowed by default. SVG can contains javascript
73 }
74
75 return $regeximgext;
76}
77
85function image_format_supported($file, $acceptsvg = 0)
86{
87 $regeximgext = getListOfPossibleImageExt();
88
89 // Case filename is not a format image
90 $reg = array();
91 if (!preg_match('/('.$regeximgext.')$/i', $file, $reg)) {
92 return -1;
93 }
94
95 // Case filename is a format image but not supported by this PHP
96 $imgfonction = '';
97 if (strtolower($reg[1]) == '.gif') {
98 $imgfonction = 'imagecreatefromgif';
99 }
100 if (strtolower($reg[1]) == '.jpg') {
101 $imgfonction = 'imagecreatefromjpeg';
102 }
103 if (strtolower($reg[1]) == '.jpeg') {
104 $imgfonction = 'imagecreatefromjpeg';
105 }
106 if (strtolower($reg[1]) == '.png') {
107 $imgfonction = 'imagecreatefrompng';
108 }
109 if (strtolower($reg[1]) == '.bmp') {
110 $imgfonction = 'imagecreatefromwbmp';
111 }
112 if (strtolower($reg[1]) == '.webp') {
113 $imgfonction = 'imagecreatefromwebp';
114 }
115 if (strtolower($reg[1]) == '.xpm') {
116 $imgfonction = 'imagecreatefromxpm';
117 }
118 if (strtolower($reg[1]) == '.xbm') {
119 $imgfonction = 'imagecreatefromxbm';
120 }
121 if (strtolower($reg[1]) == '.svg') {
122 $imgfonction = 'imagecreatefromsvg'; // Never available
123 }
124 if (strtolower($reg[1]) == '.avif') {
125 $imgfonction = 'imagecreatefromavif'; // PHP >= 8.1
126 }
127 if ($imgfonction) {
128 if (!function_exists($imgfonction)) {
129 // Functions of conversion not available in this PHP
130 return 0;
131 }
132
133 // Filename is a format image and supported for conversion by this PHP
134 return 1;
135 }
136
137 return 0;
138}
139
140
148function dol_getImageSize($file, $url = false)
149{
150 $ret = array();
151
152 if (image_format_supported($file) < 0) {
153 return $ret;
154 }
155
156 $filetoread = $file;
157 if (!$url) {
158 $filetoread = realpath(dol_osencode($file)); // Chemin canonique absolu de l'image
159 }
160
161 if ($filetoread) {
162 $infoImg = getimagesize($filetoread); // Recuperation des infos de l'image
163 if ($infoImg) {
164 $ret['width'] = $infoImg[0]; // Largeur de l'image
165 $ret['height'] = $infoImg[1]; // Hauteur de l'image
166 } else {
167 $ret['width'] = $ret['height'] = '';
168 }
169 }
170
171 return $ret;
172}
173
174
189function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, $src_y = 0, $filetowrite = '', $newquality = 0)
190{
191 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
192
193 global $langs;
194
195 dol_syslog("dol_imageResizeOrCrop file=".$file." mode=".$mode." newWidth=".$newWidth." newHeight=".$newHeight." src_x=".$src_x." src_y=".$src_y);
196
197 // Clean parameters
198 $file = trim($file);
199
200 // Check parameters
201 if (!$file) {
202 // Si le fichier n'a pas ete indique
203 return 'Bad parameter file';
204 } elseif (!file_exists($file)) {
205 // Si le fichier passe en parameter n'existe pas
206 $langs->load("errors");
207 return $langs->trans("ErrorFileNotFound", $file);
208 } elseif (image_format_supported($file) < 0) {
209 return 'This filename '.$file.' does not seem to be an image filename.';
210 } elseif (!is_numeric($newWidth) && !is_numeric($newHeight)) {
211 return 'Wrong value for parameter newWidth or newHeight';
212 } elseif ($mode == 0 && $newWidth <= 0 && $newHeight <= 0 && (empty($filetowrite) || $filetowrite == $file)) {
213 return 'At least newHeight or newWidth must be defined for resizing, or a target filename must be set to convert';
214 } elseif ($mode == 1 && ($newWidth <= 0 || $newHeight <= 0)) {
215 return 'Both newHeight or newWidth must be defined for croping';
216 }
217
218 $filetoread = realpath(dol_osencode($file)); // Chemin canonique absolu de l'image
219
220 // Get data about src image
221 // Index 0 and 1 contains respectively the width and the height of the image.
222 // Index 2 is one of the IMAGETYPE_* constants indicating the type of the image.
223 // Index 3 is a text string with the correct height="yyy" width="xxx" string that can be used directly in an IMG tag.
224 $infoImg = getimagesize($filetoread);
225 $imgWidth = $infoImg[0]; // Width of picture
226 $imgHeight = $infoImg[1]; // Height of picture
227
228 $imgTargetName = ($filetowrite ? $filetowrite : $file);
229 $newExt = strtolower(pathinfo($imgTargetName, PATHINFO_EXTENSION));
230
231 if ($mode == 0) { // If resize, we check parameters
232 if (!empty($filetowrite) && $filetowrite != $file && $newWidth <= 0 && $newHeight <= 0) {
233 $newWidth = $imgWidth;
234 $newHeight = $imgHeight;
235 }
236
237 if ($newWidth <= 0) {
238 $newWidth = intval(($newHeight / $imgHeight) * $imgWidth); // Keep ratio
239 }
240 if ($newHeight <= 0) {
241 $newHeight = intval(($newWidth / $imgWidth) * $imgHeight); // Keep ratio
242 }
243 }
244
245 // Test function to read source image exists
246 // The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
247 // They may not exists if gd extension isn't installed
248 // IMG_* and IMAGETYPE_* are different
249 // example IMG_WEBP = 32, IMAGETYPE_WEBP = 18
250 $imgfonction = '';
251 switch ($infoImg[2]) {
252 case 1: // IMAGETYPE_GIF
253 $imgfonction = 'imagecreatefromgif';
254 break;
255 case 2: // IMAGETYPE_JPG
256 $imgfonction = 'imagecreatefromjpeg';
257 break;
258 case 3: // IMAGETYPE_PNG
259 $imgfonction = 'imagecreatefrompng';
260 break;
261 case 15: // IMAGETYPE_WBMP
262 $imgfonction = 'imagecreatefromwbmp';
263 break;
264 case 18: // IMAGETYPE_WEBP
265 $imgfonction = 'imagecreatefromwebp';
266 break;
267 case 19: // IMAGETYPE_AVIF
268 $imgfonction = 'imagecreatefromavif';
269 break;
270 }
271 if ($imgfonction) {
272 if (!function_exists($imgfonction)) {
273 // Conversion functions not present in this PHP
274 return 'Read of image not possible. This PHP does not support GD functions '.$imgfonction;
275 }
276 }
277
278 // Test function to write target image exists
279 if ($filetowrite) {
280 $imgfonction = '';
281 switch ($newExt) {
282 case 'gif': // IMG_GIF
283 $imgfonction = 'imagecreatefromgif';
284 break;
285 case 'jpg': // IMG_JPG
286 case 'jpeg': // IMG_JPEG
287 $imgfonction = 'imagecreatefromjpeg';
288 break;
289 case 'png': // IMG_PNG
290 $imgfonction = 'imagecreatefrompng';
291 break;
292 case 'bmp': // IMG_WBMP
293 $imgfonction = 'imagecreatefromwbmp';
294 break;
295 case 'webp': // IMG_WEBP
296 $imgfonction = 'imagecreatefromwebp';
297 break;
298 case 'avif': // IMG_AVIF
299 $imgfonction = 'imagecreatefromavif';
300 break;
301 }
302 if ($imgfonction) {
303 if (!function_exists($imgfonction)) {
304 // Conversion functions not present in this PHP
305 return 'Write of image not possible. This PHP does not support GD functions '.$imgfonction;
306 }
307 }
308 }
309
310 // Read source image file
311 $img = null;
312 $extImg = null;
313 switch ($infoImg[2]) {
314 case 1: // Gif
315 $img = imagecreatefromgif($filetoread);
316 $extImg = '.gif'; // File name extension of image
317 break;
318 case 2: // Jpg
319 $img = imagecreatefromjpeg($filetoread);
320 $extImg = '.jpg';
321 break;
322 case 3: // Png
323 $img = imagecreatefrompng($filetoread);
324 $extImg = '.png';
325 break;
326 case 15: // Bmp
327 $img = imagecreatefromwbmp($filetoread);
328 $extImg = '.bmp';
329 break;
330 case 18: // Webp
331 $img = imagecreatefromwebp($filetoread);
332 $extImg = '.webp';
333 break;
334 }
335
336 if ($img === null) {
337 return "Error: Could not create Image from '$filetoread'";
338 }
339
340 // Create empty image for target
341 if ($newExt == 'gif') {
342 // Compatibility image GIF
343 $imgTarget = imagecreate($newWidth, $newHeight);
344 } else {
345 $imgTarget = imagecreatetruecolor($newWidth, $newHeight);
346 }
347
348 // Activate antialiasing for better quality
349 if (function_exists('imageantialias')) {
350 imageantialias($imgTarget, true);
351 }
352
353 // This is to keep transparent alpha channel if exists (PHP >= 4.2)
354 if (function_exists('imagesavealpha')) {
355 imagesavealpha($imgTarget, true);
356 }
357
358 // Set transparent color according to image extension
359 $trans_colour = -1; // By default, undefined
360 switch ($newExt) {
361 case 'gif': // Gif
362 $trans_colour = imagecolorallocate($imgTarget, 255, 255, 255); // The method is different for the GIF format
363 imagecolortransparent($imgTarget, $trans_colour);
364 break;
365 case 'jpg': // Jpg
366 case 'jpeg': // Jpeg
367 $trans_colour = imagecolorallocatealpha($imgTarget, 255, 255, 255, 0);
368 break;
369 case 'png': // Png
370 imagealphablending($imgTarget, false); // For compatibility with certain systems
371 $trans_colour = imagecolorallocatealpha($imgTarget, 255, 255, 255, 127); // Keep transparent channel
372 break;
373 case 'bmp': // Bmp
374 $trans_colour = imagecolorallocatealpha($imgTarget, 255, 255, 255, 0);
375 break;
376 case 'webp': // Webp
377 $trans_colour = imagecolorallocatealpha($imgTarget, 255, 255, 255, 127);
378 break;
379 }
380 if (function_exists("imagefill") && $trans_colour > 0) {
381 imagefill($imgTarget, 0, 0, $trans_colour);
382 }
383
384 dol_syslog("dol_imageResizeOrCrop: convert image from ($imgWidth x $imgHeight) at position ($src_x x $src_y) to ($newWidth x $newHeight) as a $extImg");
385 //imagecopyresized($imgTarget, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imgWidth, $imgHeight); // Insere l'image de base redimensionnee
386 imagecopyresampled($imgTarget, $img, 0, 0, $src_x, $src_y, $newWidth, $newHeight, ($mode == 0 ? $imgWidth : $newWidth), ($mode == 0 ? $imgHeight : $newHeight)); // Insere l'image de base redimensionnee
387
388 // Check if permission are ok
389 //$fp = fopen($imgTargetName, "w");
390 //fclose($fp);
391
392 // Create image on disk (overwrite file if exists)
393 switch ($newExt) {
394 case 'gif': // Gif
395 $newquality = 'NU'; // Quality is not used for this format
396 imagegif($imgTarget, $imgTargetName);
397 break;
398 case 'jpg': // Jpg
399 case 'jpeg': // Jpeg
400 $newquality = ($newquality ? $newquality : '100'); // % quality maximum
401 imagejpeg($imgTarget, $imgTargetName, $newquality);
402 break;
403 case 'png': // Png
404 $newquality = 0; // No compression (0-9)
405 imagepng($imgTarget, $imgTargetName, $newquality);
406 break;
407 case 'bmp': // Bmp
408 $newquality = 'NU'; // Quality is not used for this format
409 imagewbmp($imgTarget, $imgTargetName);
410 break;
411 case 'webp': // Webp
412 $newquality = ($newquality ? $newquality : '100'); // % quality maximum
413 imagewebp($imgTarget, $imgTargetName, $newquality);
414 break;
415 default:
416 dol_syslog("images.lib.php::imageResizeOrCrop() Format ".$newExt." is not supported", LOG_WARNING);
417 }
418
419 // Set permissions on file
420 dolChmod($imgTargetName);
421
422 // Free memory. This does not delete image.
423 if ($img) {
424 imagedestroy($img);
425 }
426 if ($imgTarget) {
427 imagedestroy($imgTarget);
428 }
429
430 clearstatcache(); // File was replaced by a modified one, so we clear file caches.
431
432 return $imgTargetName;
433}
434
435
444function dolRotateImage($file_path)
445{
446 return correctExifImageOrientation($file_path, $file_path);
447}
448
449
458function correctExifImageOrientation($fileSource, $fileDest, $quality = 95)
459{
460 if (function_exists('exif_read_data')) {
461 $exif = @exif_read_data($fileSource);
462 if ($exif && isset($exif['Orientation'])) {
463 $infoImg = getimagesize($fileSource); // Get image infos
464
465 $orientation = $exif['Orientation'];
466 if ($orientation != 1) {
467 $img = imagecreatefromjpeg($fileSource);
468 $deg = 0;
469 switch ($orientation) {
470 case 3:
471 $deg = 180;
472 break;
473 case 6:
474 $deg = 270;
475 break;
476 case 8:
477 $deg = 90;
478 break;
479 }
480 if ($deg) {
481 if ($infoImg[2] === IMAGETYPE_PNG) { // In fact there is no exif on PNG but just in case
482 imagealphablending($img, false);
483 imagesavealpha($img, true);
484 $img = imagerotate($img, $deg, imagecolorallocatealpha($img, 0, 0, 0, 127));
485 imagealphablending($img, false);
486 imagesavealpha($img, true);
487 } else {
488 $img = imagerotate($img, $deg, 0);
489 }
490 }
491 // then rewrite the rotated image back to the disk as $fileDest
492 if ($fileDest === false) {
493 return $img;
494 } else {
495 // In fact there exif is only for JPG but just in case
496 // Create image on disk
497 $image = false;
498
499 switch ($infoImg[2]) {
500 case IMAGETYPE_GIF: // 1
501 $image = imagegif($img, $fileDest);
502 break;
503 case IMAGETYPE_JPEG: // 2
504 $image = imagejpeg($img, $fileDest, $quality);
505 break;
506 case IMAGETYPE_PNG: // 3
507 $image = imagepng($img, $fileDest, $quality);
508 break;
509 case IMAGETYPE_BMP: // 6
510 // Not supported by PHP GD
511 break;
512 case IMAGETYPE_WBMP: // 15
513 $image = imagewbmp($img, $fileDest);
514 break;
515 }
516
517 // Free up memory (imagedestroy does not delete files):
518 @imagedestroy($img);
519
520 return $image;
521 }
522 } // if there is some rotation necessary
523 } // if have the exif orientation info
524 } // if function exists
525
526 return false;
527}
528
543function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', $quality = 50, $outdir = 'thumbs', $targetformat = 0)
544{
545 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
546
547 global $langs;
548
549 dol_syslog("vignette file=".$file." extName=".$extName." maxWidth=".$maxWidth." maxHeight=".$maxHeight." quality=".$quality." outdir=".$outdir." targetformat=".$targetformat);
550
551 // Clean parameters
552 $file = dol_sanitizePathName(trim($file));
553
554 // Check parameters
555 if (!$file) {
556 // If the file has not been indicated
557 return 'ErrorBadParameters';
558 } elseif (image_format_supported($file) < 0) {
559 dol_syslog('This file '.$file.' does not seem to be a supported image file name (bad extension).', LOG_WARNING);
560 return 'ErrorBadImageFormat';
561 } elseif (!is_numeric($maxWidth) || empty($maxWidth) || $maxWidth < -1) {
562 // If max width is incorrect (not numeric, empty, or less than 0)
563 dol_syslog('Wrong value for parameter maxWidth', LOG_ERR);
564 return 'Error: Wrong value for parameter maxWidth';
565 } elseif (!is_numeric($maxHeight) || empty($maxHeight) || $maxHeight < -1) {
566 // If max height is incorrect (not numeric, empty, or less than 0)
567 dol_syslog('Wrong value for parameter maxHeight', LOG_ERR);
568 return 'Error: Wrong value for parameter maxHeight';
569 }
570
571 $filetoread = realpath(dol_osencode($file)); // Absolute canonical path of image
572
573 if (!file_exists($filetoread)) {
574 // If the file passed in parameter does not exist
575 $langs->load("errors");
576 dol_syslog($langs->trans("ErrorFileNotFound", $filetoread), LOG_ERR);
577 return $langs->trans("ErrorFileNotFound", $filetoread);
578 }
579
580 $infoImg = getimagesize($filetoread); // Get information like size and real format of image. Warning real format may be png when extension is .jpg
581 $imgWidth = $infoImg[0]; // Width of image
582 $imgHeight = $infoImg[1]; // Height of image
583
584 // TODO LDR
585 //if $infoImg[2] != extension of file $file, return a string 'Error: content of file has a format that differs of the format of its extension
586
587 $ort = false;
588 if (function_exists('exif_read_data')) {
589 $exif = @exif_read_data($filetoread);
590 if ($exif && !empty($exif['Orientation'])) {
591 $ort = $exif['Orientation'];
592 }
593 }
594
595 if ($maxWidth == -1) {
596 $maxWidth = $infoImg[0]; // If size is -1, we keep unchanged
597 }
598 if ($maxHeight == -1) {
599 $maxHeight = $infoImg[1]; // If size is -1, we keep unchanged
600 }
601
602 // If the image is smaller than the maximum width and height, no thumbnail is created.
603 if ($infoImg[0] < $maxWidth && $infoImg[1] < $maxHeight) {
604 // we always create thumbnails
605 dol_syslog("File size is smaller than thumb size", LOG_DEBUG);
606 // return 'Le fichier '.$file.' ne necessite pas de creation de vignette';
607 }
608
609 $imgfonction = '';
610 switch ($infoImg[2]) {
611 case IMAGETYPE_GIF: // 1
612 $imgfonction = 'imagecreatefromgif';
613 break;
614 case IMAGETYPE_JPEG: // 2
615 $imgfonction = 'imagecreatefromjpeg';
616 break;
617 case IMAGETYPE_PNG: // 3
618 $imgfonction = 'imagecreatefrompng';
619 break;
620 case IMAGETYPE_BMP: // 6
621 // Not supported by PHP GD
622 $imgfonction = '';
623 break;
624 case IMAGETYPE_WBMP: // 15
625 $imgfonction = 'imagecreatefromwbmp';
626 break;
627 case IMAGETYPE_WEBP: // 18
628 $imgfonction = 'imagecreatefromwebp';
629 break;
630 case 19: // 19 TYPEIMAGE_AVIF constant don't exists with php < 8.1
631 $imgfonction = 'imagecreatefromavif';
632 break;
633 default:
634 $imgfonction = '';
635 }
636 if ($imgfonction) {
637 if (!function_exists($imgfonction)) {
638 // Conversion functions not present in this PHP
639 return 'Error: Creation of thumbs not possible. This PHP does not support GD function '.$imgfonction;
640 }
641 }
642
643 // We create the directory containing the thumbnails
644 $dirthumb = dirname($file).($outdir ? '/'.$outdir : ''); // Path to thumbnail folder
645 dol_mkdir($dirthumb);
646
647 // Variable initialization according to image extension
648 $img = null;
649 $extImg = null;
650 switch ($infoImg[2]) {
651 case IMAGETYPE_GIF: // 1
652 $img = imagecreatefromgif($filetoread);
653 $extImg = '.gif';
654 break;
655 case IMAGETYPE_JPEG: // 2
656 $img = imagecreatefromjpeg($filetoread);
657 $extImg = (preg_match('/\.jpeg$/', $file) ? '.jpeg' : '.jpg');
658 break;
659 case IMAGETYPE_PNG: // 3
660 $img = imagecreatefrompng($filetoread);
661 $extImg = '.png';
662 break;
663 case IMAGETYPE_BMP: // 6
664 // Not supported by PHP GD
665 $extImg = '.bmp';
666 break;
667 case IMAGETYPE_WBMP: // 15
668 $img = imagecreatefromwbmp($filetoread);
669 $extImg = '.bmp';
670 break;
671 case IMAGETYPE_WEBP: // 18
672 $img = imagecreatefromwebp($filetoread);
673 $extImg = '.webp';
674 break;
675 case 19: // 19 TYPEIMAGE_AVIF constant don't exists with php < 8.1
676 $img = imagecreatefromavif($filetoread);
677 $extImg = '.avif';
678 break;
679 }
680
681 // Before PHP8, img was a resource, With PHP8, it is a GdImage
682 // if (!is_resource($img) && class_exists('GdImage') && !($img instanceof GdImage)) {
683 if (is_null($img) || $img === false) {
684 dol_syslog('Failed to detect type of image. We found infoImg[2]='.$infoImg[2], LOG_WARNING);
685 return 0;
686 }
687
688 $exifAngle = false;
689 if ($ort && getDolGlobalString('MAIN_USE_EXIF_ROTATION')) {
690 switch ($ort) {
691 case 3: // 180 rotate left
692 $exifAngle = 180;
693 break;
694 case 6: // 90 rotate right
695 $exifAngle = -90;
696 // changing sizes
697 $trueImgWidth = $infoImg[1];
698 $trueImgHeight = $infoImg[0];
699 break;
700 case 8: // 90 rotate left
701 $exifAngle = 90;
702 // changing sizes
703 $trueImgWidth = $infoImg[1]; // Largeur de l'image
704 $trueImgHeight = $infoImg[0]; // Hauteur de l'image
705 break;
706 }
707 }
708
709 if ($exifAngle) {
710 $rotated = false;
711
712 if ($infoImg[2] === IMAGETYPE_PNG) { // In fact there is no exif on PNG but just in case
713 imagealphablending($img, false);
714 imagesavealpha($img, true);
715 $rotated = imagerotate($img, $exifAngle, imagecolorallocatealpha($img, 0, 0, 0, 127));
716 imagealphablending($rotated, false);
717 imagesavealpha($rotated, true);
718 } else {
719 $rotated = imagerotate($img, $exifAngle, 0);
720 }
721
722 // replace image with good orientation
723 if (!empty($rotated) && isset($trueImgWidth) && isset($trueImgHeight)) {
724 $img = $rotated;
725 $imgWidth = $trueImgWidth;
726 $imgHeight = $trueImgHeight;
727 }
728 }
729
730 // Initialize thumbnail dimensions if larger than original
731 if ($maxWidth > $imgWidth) {
732 $maxWidth = $imgWidth;
733 }
734 if ($maxHeight > $imgHeight) {
735 $maxHeight = $imgHeight;
736 }
737
738 $whFact = $maxWidth / $maxHeight; // Width/height factor for maximum label dimensions
739 $imgWhFact = $imgWidth / $imgHeight; // Original width/height factor
740
741 // Set label dimensions
742 if ($whFact < $imgWhFact) {
743 // If determining width
744 $thumbWidth = $maxWidth;
745 $thumbHeight = $thumbWidth / $imgWhFact;
746 } else {
747 // If determining height
748 $thumbHeight = $maxHeight;
749 $thumbWidth = $thumbHeight * $imgWhFact;
750 }
751 $thumbHeight = (int) round($thumbHeight);
752 $thumbWidth = (int) round($thumbWidth);
753
754 // Define target format
755 if (empty($targetformat)) {
756 $targetformat = $infoImg[2];
757 }
758
759 // Create empty image
760 if ($targetformat == IMAGETYPE_GIF) {
761 // Compatibilite image GIF
762 $imgThumb = imagecreate($thumbWidth, $thumbHeight);
763 } else {
764 $imgThumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
765 }
766
767 // Activate antialiasing for better quality
768 if (function_exists('imageantialias')) {
769 imageantialias($imgThumb, true);
770 }
771
772 // This is to keep transparent alpha channel if exists (PHP >= 4.2)
773 if (function_exists('imagesavealpha')) {
774 imagesavealpha($imgThumb, true);
775 }
776
777 // Variable initialization according to image extension
778 // $targetformat is 0 by default, in such case, we keep original extension
779 $extImgTarget = ''; // Default = same extension as original
780 $trans_colour = false;
781 $newquality = null;
782 switch ($targetformat) {
783 case IMAGETYPE_GIF: // 1
784 $trans_colour = imagecolorallocate($imgThumb, 255, 255, 255); // The GIF format works differently
785 imagecolortransparent($imgThumb, $trans_colour);
786 $extImgTarget = '.gif';
787 $newquality = 'NU';
788 break;
789 case IMAGETYPE_JPEG: // 2
790 $trans_colour = imagecolorallocatealpha($imgThumb, 255, 255, 255, 0);
791 $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '.jpg');
792 $newquality = $quality;
793 break;
794 case IMAGETYPE_PNG: // 3
795 imagealphablending($imgThumb, false); // For compatibility on certain systems
796 $trans_colour = imagecolorallocatealpha($imgThumb, 255, 255, 255, 127); // Keep transparent channel
797 $extImgTarget = '.png';
798 $newquality = round(abs($quality - 100) * 9 / 100);
799 break;
800 case IMAGETYPE_BMP: // 6
801 // Not supported by PHP GD
802 $extImgTarget = '.bmp';
803 $newquality = 'NU';
804 break;
805 case IMAGETYPE_WBMP: // 15
806 $trans_colour = imagecolorallocatealpha($imgThumb, 255, 255, 255, 0);
807 $extImgTarget = '.bmp';
808 $newquality = 'NU';
809 break;
810 case IMAGETYPE_WEBP: // 18
811 $trans_colour = imagecolorallocatealpha($imgThumb, 255, 255, 255, 0);
812 $extImgTarget = '.webp';
813 $newquality = $quality;
814 break;
815 case 19: // 19 TYPEIMAGE_AVIF constant don't exists with php < 8.1
816 $trans_colour = imagecolorallocatealpha($imgThumb, 255, 255, 255, 0);
817 $extImgTarget = '.avif';
818 $newquality = $quality;
819 break;
820 }
821 if (function_exists("imagefill") && $trans_colour !== false) {
822 imagefill($imgThumb, 0, 0, $trans_colour);
823 }
824
825 dol_syslog("vignette: convert image from ($imgWidth x $imgHeight) to ($thumbWidth x $thumbHeight) as $extImg, newquality=$newquality");
826 //imagecopyresized($imgThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imgWidth, $imgHeight); // Insert resized base image
827 imagecopyresampled($imgThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imgWidth, $imgHeight); // Insert resized base image
828
829 $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.avif)$/i', '', $file); // We remove any extension box
830 $fileName = basename($fileName);
831 //$imgThumbName = $dirthumb.'/'.getImageFileNameForSize(basename($file), $extName, $extImgTarget); // Full path of thumb file
832 $imgThumbName = getImageFileNameForSize($file, $extName, $extImgTarget); // Full path of thumb file
833
834
835 // Check if permission are ok
836 //$fp = fopen($imgThumbName, "w");
837 //fclose($fp);
838
839 // Create image on disk
840 switch ($targetformat) {
841 case IMAGETYPE_GIF: // 1
842 imagegif($imgThumb, $imgThumbName);
843 break;
844 case IMAGETYPE_JPEG: // 2
845 imagejpeg($imgThumb, $imgThumbName, $newquality); // @phan-suppress-current-line PhanTypeMismatchArgumentNullableInternal,PhanPossiblyUndeclaredVariable
846 break;
847 case IMAGETYPE_PNG: // 3
848 imagepng($imgThumb, $imgThumbName, !is_numeric($newquality) ? -1 : (int) $newquality); // @phan-suppress-current-line PhanPossiblyUndeclaredVariable
849 break;
850 case IMAGETYPE_BMP: // 6
851 // Not supported by PHP GD
852 break;
853 case IMAGETYPE_WBMP: // 15
854 imagewbmp($imgThumb, $imgThumbName);
855 break;
856 case IMAGETYPE_WEBP: // 18
857 imagewebp($imgThumb, $imgThumbName, $newquality); // @phan-suppress-current-line PhanTypeMismatchArgumentNullableInternal,PhanPossiblyUndeclaredVariable
858 break;
859 case 19: // 19 TYPEIMAGE_AVIF constant don't exists with php < 8.1
860 imageavif($imgThumb, $imgThumbName, $newquality); // @phan-suppress-current-line PhanTypeMismatchArgumentNullableInternal,PhanPossiblyUndeclaredVariable
861 break;
862 }
863
864 // Set permissions on file
865 dolChmod($imgThumbName);
866
867 // Free memory. This does not delete image.
868 imagedestroy($img);
869 imagedestroy($imgThumb);
870
871 return $imgThumbName;
872}
873
874
883function imgAddEditDeleteButton($htmlid, $urledit, $urldelete)
884{
885 // TODO
886 return '';
887}
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_sanitizePathName($str, $newstr='_', $unaccent=0, $allowdash=0)
Clean a string to use it as a path name.
dolChmod($filepath, $newmask='')
Change mod of a file.
getImageFileNameForSize($file, $extName, $extImgTarget='')
Return the filename of file to get the thumbs.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
vignette($file, $maxWidth=160, $maxHeight=120, $extName='_small', $quality=50, $outdir='thumbs', $targetformat=0)
Create a thumbnail from an image file (Supported extensions are gif, jpg, png and bmp).
getListOfPossibleImageExt($acceptsvg=0)
Return if a filename is file name of a supported image format.
if(!defined( 'IMAGETYPE_WEBP')) getDefaultImageSizes()
Return default values for image sizes.
correctExifImageOrientation($fileSource, $fileDest, $quality=95)
Add exif orientation correction for image.
dolRotateImage($file_path)
dolRotateImage if image is a jpg file.
dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x=0, $src_y=0, $filetowrite='', $newquality=0)
Resize or crop an image file (Supported extensions are gif, jpg, png, bmp and webp)
dol_getImageSize($file, $url=false)
Return size of image file on disk (Supported extensions are gif, jpg, png, bmp and webp)
imgAddEditDeleteButton($htmlid, $urledit, $urldelete)
Beautify an image by adding a link edit and delete on image.
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.