IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Langage PHP Discussion :

Recadrage proportionnel image


Sujet :

Langage PHP

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre éprouvé
    Profil pro
    Inscrit en
    Avril 2005
    Messages
    818
    Détails du profil
    Informations personnelles :
    Âge : 41
    Localisation : France, Drôme (Rhône Alpes)

    Informations forums :
    Inscription : Avril 2005
    Messages : 818
    Par défaut Recadrage proportionnel image
    Bonjour,

    Je cherche à faire un recadrage d'une image.
    En gros, je veux faire une prévisualisation d'un poster en php.
    J'ai du mal avec les proportions pixel et cm...

    En gros, si je veux un poster de 30x40 cm.
    Je fais un cadre d'une dimension proportionnelle en pixel (par exemple 300x400 pixels).
    Si mon image est plus haute que large, je fixe la largeur de l'image à 400 pixels, et si mon image est plus large que haute, je fixe la hauteur de l'image à 300 pixels. Sans préciser l'autre mesure de manière à ce que l'image s'affiche non déformée...

    Puis il ne reste plus qu'à faire glisser le cadre dans la hauteur (ou la largeur) de l'image pour faire le recadrage sur la partie de l'image que l'on veut...

    Mais est ce que ce recadrage sera proportionnel à l'image au final?
    J'avoue que j'ai du mal à comprendre le passage de pixel en cm...

    Est ce que quelqu'un peut m'aider à poser mon résonnement correctement svp?

  2. #2
    Membre chevronné
    Profil pro
    Inscrit en
    Juillet 2003
    Messages
    343
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2003
    Messages : 343
    Par défaut
    Ben c'est pas simple la hauteur d'1pixel est différente de la largeur!
    J'ai eu ce problème y'a des années en Delphi, pour des sorties papiers de graphique scientifique (type milimétrée) et la solution était de passer par des librairie spécifique pour rétablir les proportions en fonction de la résolution écran ET imprimante (pitch/pouce etc...) et/ou bien se plonger dans las API win32...à l'époque!

    J'attends la réponse des experts 'guru' du forum avec impatience!

  3. #3
    Membre Expert
    Avatar de ThomasR
    Homme Profil pro
    Directeur technique
    Inscrit en
    Décembre 2007
    Messages
    2 230
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Directeur technique
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Décembre 2007
    Messages : 2 230
    Par défaut
    Citation Envoyé par calitom Voir le message
    Bonjour,

    Je cherche à faire un recadrage d'une image.
    En gros, je veux faire une prévisualisation d'un poster en php.
    J'ai du mal avec les proportions pixel et cm...
    Bonjour,

    Pourquoi cherches-tu à convertir cm en px ? Cela ne t'apportes rien dans la gestion des proportions.

    Si tu veux afficher une image de largeur 300pixels sans qu'elle soit déformée il te suffit d'appliquer sur la hauteur le ratio de proportion : ancienne largeur / nouvelle largeur.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    $img_path = '/images/visuel.jpeg';
    $sizes = getimagesize($img_path);
    $width = $sizes[0];
    $height = $sizes[1];
     
    $newwidth = 300;
    $newheight = $height / ($sizes[0] / $newwidth);
     
    echo '<img src="'.$img_path.'" width="'.$newwidth.'" height="'.$newheight.'"/>';

  4. #4
    Membre éprouvé
    Profil pro
    Inscrit en
    Avril 2005
    Messages
    818
    Détails du profil
    Informations personnelles :
    Âge : 41
    Localisation : France, Drôme (Rhône Alpes)

    Informations forums :
    Inscription : Avril 2005
    Messages : 818
    Par défaut
    Ok, mais je veux que le résultat du recadrage fasse (dans l'exemple ci-dessus) 30x40cm...

    Alors vu que mon image est en pixel, je n'arrive pas à comprendre comment faire pour que l'image finale fasse 30x40cm alors que je selectionne le cadrage avec des dimensions en pixels...

    Je dis peut etre n'importe quoi, mais c'est assez flou dans ma tête... lol

  5. #5
    Membre Expert
    Avatar de ThomasR
    Homme Profil pro
    Directeur technique
    Inscrit en
    Décembre 2007
    Messages
    2 230
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Directeur technique
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Décembre 2007
    Messages : 2 230
    Par défaut
    Citation Envoyé par calitom Voir le message
    Ok, mais je veux que le résultat du recadrage fasse (dans l'exemple ci-dessus) 30x40cm...

    Alors vu que mon image est en pixel, je n'arrive pas à comprendre comment faire pour que l'image finale fasse 30x40cm alors que je selectionne le cadrage avec des dimensions en pixels...

    Je dis peut etre n'importe quoi, mais c'est assez flou dans ma tête... lol
    Le pixel n'est pas une unité de mesure fixe. Le nombre de pixels par centimètre au carré dépend de la résolution d'écran.

    Ainsi un centimère au carré ne sera pas couvert par le même nombre de pixels suivant suivant si tu es 640x480 ou en 1600x1200.

    Tu souhaites que le resultat du cadrage fasse 30 x 40cm, pas possible, mais tu peux faire en sorte que le resultat du cadrage ait pour proportion 3 / 4...Et pour cela il te suffit d'appliquer l'algorythme que j'ai saisi plus haut.

  6. #6
    Membre éprouvé
    Profil pro
    Inscrit en
    Avril 2005
    Messages
    818
    Détails du profil
    Informations personnelles :
    Âge : 41
    Localisation : France, Drôme (Rhône Alpes)

    Informations forums :
    Inscription : Avril 2005
    Messages : 818
    Par défaut
    J'ai trouvé un site qui fait ce que je veux faire, mais en flash...

    Voici l'url d'un cadre de 30x40cm:http://www.mydesign.com/prod~idp~80.html

    Comment faire la même chose en php?

    Ils proposent bien un recadrage de l'image avec un cadre sur la photo qui symbolise le cadre de 30x40cm...

  7. #7
    Membre Expert
    Avatar de ThomasR
    Homme Profil pro
    Directeur technique
    Inscrit en
    Décembre 2007
    Messages
    2 230
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Directeur technique
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Décembre 2007
    Messages : 2 230
    Par défaut
    Bonsoir,

    Ok je viens de comprendre, tu cherches en effet à recadrer ton image (image cropping).

    Si tu veux j'ai une classe qui te permet de faire du recadrage (cropping), par contre je n'autorise pas la saisie des coordonnées du cadre de recadrage, il est automatiquement placé au centre de l'image source, tu vas comprendre :

    Voici la classe thumbs_builder, c'est une classe outil qui permet de retravailler des images pour en générer des miniatures :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
     
    <?php
    /*
    Author : Thomas RAMBAUD
    Year : 2009
    Version : 1.1
    Free to use
    */
     
    class thumbs_builder {
     
        private $_source,
            $_thumbs_quality,
            $_save_directory,
            $_border,
            $_text,
            $_icon,
            $_current_thumb;
     
        function __construct($source_src, $save_directory, $thumbs_quality=100){
            $this->set_source_src($source_src);
            $this->set_save_directory($save_directory);
            $this->set_thumbs_quality($thumbs_quality);
            $this->_background_src = null;
            $this->_icon = null;
            $this->_current_thumb = null;
            $this->_border = null;
            $this->_text = null;
        }
     
        //-----------
        // PROPERTIES
        //-----------
     
          // Getters
     
          function get_source_path(){
              return $this->_source['src'];
          }
     
          function get_source_width(){
              return $this->_source['sizes'][0];
          }
     
          function get_source_height(){
              return $this->_source['sizes'][1];
          }
     
          function get_save_directory(){
              return $this->_save_directory;
          }
     
          function get_current_thumb(){
              return $this->_current_thumb['img'];
          }
     
          function get_current_thumb_width(){
              return $this->_current_thumb['sizes'][0];
          }
     
          function get_current_thumb_height(){
              return $this->_current_thumb['sizes'][1];
          }
     
          static function get_random_string($chars_count = 4){
              $caracteres = "123AaBbCcDdEe456fGgHhIiJjKkLlMmNn789PQqRrSsTtUuVvWwXxYyZz0";
              $chaine = '';
              srand(time());
              for ($i=0;$i<$chars_count;$i++){
                  $chaine.=substr($caracteres, rand()%(strlen($caracteres)), 1);
              }
              return $chaine;
          }
     
          static function get_image_extension($fn_or_path){
              return strtolower(substr($fn_or_path, strrpos($fn_or_path, '.') + 1));
          }
     
          static function get_rgb_from_hexa($hex){
              if($hex[0] == '#'){
                  $hex = substr($hex,1);
              }
              $nb_cars = strlen($hex);
              if($nb_cars == 6){
                  list($r, $g, $b) = array($hex[0].$hex[1], $hex[2].$hex[3], $hex[4].$hex[5]);
              }
              elseif($nb_cars == 3){
                  list($r, $g, $b) = array($hex[0].$hex[0], $hex[1].$hex[1], $hex[2].$hex[2]);
              }
              else{
                  return false;
              }
              $r = hexdec($r); $g = hexdec($g); $b = hexdec($b);
              return array($r, $g, $b);
          }
     
          // Setters
     
          function set_source_src($source_src){
              if(is_file($source_src)){
                  $this->_source['src'] = $source_src;
                  $this->_source['img'] = $this->build_image_from_path($source_src);
                  $this->_source['sizes'] = getimagesize($source_src);
                  return true;
              }
              else{
                 die('L\'image source définie n\'existe pas : <span style="color:red">'.$source_src.'</span>');
              }
          }
     
          function set_save_directory($save_directory){
              if(is_dir($save_directory)){
                  $this->_save_directory = $save_directory;
                  return true;
              }
              else{
                  die('Le dossier d\'enregistrement des miniatures n\'existe pas : <span style="color:red">'.$save_directory.'</span>');
              }
          }
     
          function set_thumbs_quality($quality){
              if(intval($quality)){
                  $this->_thumbs_quality = $quality;
                  return true;
              }
              else{
                  die('La qualité des miniatures à pour valeur un nombre compris entre 0 et 100 : <span style="color:red">'.$quality.'</span>');
              }
          }
     
          function set_icon($icon_src, $position_top, $position_left, $alpha=null){
             if(is_file($icon_src)){
                 $this->_icon['src'] = $icon_src;
                 $this->_icon['sizes'] = getimagesize($icon_src);
                 $this->set_icon_position($position_top, $position_left);
                 $this->_icon['img'] = $this->build_image_from_path($icon_src);
                 if($alpha != null) $this->set_icon_alpha($alpha);
                 return true;
             }
             else{
                 die('Le fichier image de l\'icône est inexistant ou n\'est pas un fichier : <span style="color:red">'.$icon_src.'</span>');
             }
          }
     
          function set_icon_alpha($alpha){
              if(intval($alpha)){
                  $this->_icon['alpha'] = $alpha;
                  return true;
              }
              else{
                  die('L\'opacité alpha de l\'icone doit être un nombre compris entre 0 et 100 : <span style="color:red">'.$alpha.'</span>');
              }
          }
     
          function set_icon_position($position_top, $position_left){
              $err_positions = 'Les positions autorisées sont "top", "bottom", "left", "right" et "center"';
              $allowed_positions = Array('top', 'bottom', 'left', 'right', 'center');
              if(in_array($position_top, $allowed_positions)){
                  $this->_icon['position_top'] = $position_top;
                  if(in_array($position_left, $allowed_positions)){
                      $this->_icon['position_left'] = $position_left;
                      return true;
                  }
                  else{
                      die($err_positions.' : <span style="color:red">'.$position_left.'</span>');
                  }
              }
              else{
                  die($err_positions.' : <span style="color:red">'.$position_top.'</span>');
              }
          }
     
          function set_icon_autoresize($bool){
              if(!is_bool($bool)) die('La fonction set_icon_autoresize n\'accepte que des booléens : true / false');
              $this->_icon['autoresize'] = $bool;
          }
     
          function set_text($text, $position_top, $position_left, $hex_color, $size = 20){
              if($text != null){
                  $this->_text['text'] = $text;
                  $err_positions = 'Les positions autorisées sont "top", "bottom", "left", "right" et "center"';
                  $allowed_positions = Array('top','bottom','left','right','center');
                  if(in_array($position_top, $allowed_positions)){
                      $this->_text['position_top'] = $position_top;
                      if(in_array($position_left, $allowed_positions)){
                          $this->_text['position_left'] = $position_left;
                          $this->set_text_size($size);
                          $this->set_text_font(3);
                          $this->set_text_color($hex_color);
                          $this->reload_text_sizes();
                          return true;  
                      } 
                      else{
                          die($err_positions.' : <span style="color:red">'.$position_left.'</span>');   
                      }
                  } 
                  else{
                      die($err_positions.' : <span style="color:red">'.$position_top.'</span>');    
                  }
              }          
          }
     
          function set_text_color($hex){
              $this->_text['color'] = $this->get_rgb_from_hexa($hex);   
          }
     
          function set_text_font($font){
                  $this->_text['font'] = $font;
                  $this->reload_text_sizes();
          }
     
          function set_text_size($size){
              if(is_int($size)){
                  $this->_text['size'] = $size;
                  $this->reload_text_sizes();   
              }
          }    
     
          function set_text_autoresize($bool){
              if(!is_bool($bool)) die('La fonction set_text_autoresize n\'accepte que des booléens : true / false');
              $this->_text['autoresize'] = $bool;   
          }
     
          function set_text_shadow($bool){
              if(!is_bool($bool)) die('La fonction set_text_shadow n\'accepte que des booléens : true / false');
              $this->_text['shadow'] = $bool;       
          } 
     
          function remove_icon(){
            $this->_icon = null;
          }
     
          function remove_text(){
            $this->_text = null;
          }
     
        // ----------------
        // PUBLIC FUNCTIONS
        // ----------------
     
           // Resize the source bitmap in a layer with a background color
     
           function resize($thumb_width, $thumb_height, $background_color, $filename = null){
               try {
                   $this->clear_current_thumb();
     
                   $this->_current_thumb['img'] = imagecreatetruecolor($thumb_width,$thumb_height);
                   $this->_current_thumb['sizes'][0] = $thumb_width;
                   $this->_current_thumb['sizes'][1] = $thumb_height;
     
                   $color = $this->get_rgb_from_hexa($background_color);
                   $color = imagecolorallocate($this->_current_thumb['img'],$color[0],$color[1],$color[2]);
                   imagefill($this->_current_thumb['img'], 0, 0 , $color);
     
                   $ratio_source = $this->_source['sizes'][0] / $this->_source['sizes'][1];
                   $ratio_x = $this->_source['sizes'][0] / $thumb_width;
                   $ratio_y = $this->_source['sizes'][1] / $thumb_height;
     
                   $margin_left = 0;
                   $margin_top = 0;
     
                   if ($ratio_x > $ratio_y){
                       $img_width = $thumb_width;
                       $img_height = $thumb_width / $ratio_source;
                       $margin_top = $thumb_height / 2 - $img_height / 2;
                   }
                   elseif($ratio_x < $ratio_y){
                       $img_height = $thumb_height;
                       $img_width = $thumb_height * $ratio_source;
                       $margin_left = $thumb_width / 2 - $img_width / 2;
                   }
                   else{
                       $img_width = $thumb_width;
                       $img_height = $thumb_height;
                   }
     
                   $thumb = imagecreatetruecolor($img_width,$img_height);
                   imagecopyresized($thumb, $this->_source['img'], 0, 0, 0, 0, $img_width, $img_height, $this->_source['sizes'][0], $this->_source['sizes'][1]);
                   imagecopymerge($this->_current_thumb['img'], $thumb, $margin_left, $margin_top, 0, 0, $img_width, $img_height, 100);
                   if(!is_null($filename)){
                       return $this->save($filename);
                   }
                   else{
                       return true; 
                   }
               }
               catch (Exception $e) {
                   die($e->__toString().'. Impossible de redimensionner l\'image à partir des dimensions voulues : '.$thumb_width.' * '.$thumb_height); 
               }
           }
     
           // Crop then resize the source bitmap in the current bitmap
     
           function resize_crop($thumb_width, $thumb_height, $filename = null){
               try {
                   $this->clear_current_thumb();
     
                   $this->_current_thumb['img'] = imagecreatetruecolor($thumb_width, $thumb_height);
                   $this->_current_thumb['sizes'][0] = $thumb_width;
                   $this->_current_thumb['sizes'][1] = $thumb_height;
     
                   $ratio_x = $this->_source['sizes'][0] / $thumb_width;
                   $ratio_y = $this->_source['sizes'][1] / $thumb_height;
     
                   $mid_height = $thumb_height / 2;
                   $mid_width = $thumb_width / 2;
     
                   if($ratio_x > $ratio_y){
                       $final_width = $this->_source['sizes'][0] / $ratio_y;
                       $int_width = ($final_width / 2) - $mid_width;
                       imagecopyresampled($this->_current_thumb['img'],$this->_source['img'],-$int_width,0,0,0,$final_width,$thumb_height,$this->_source['sizes'][0],$this->_source['sizes'][1]);
                   }
                   elseif($ratio_x < $ratio_y){
                       $final_height = $this->_source['sizes'][1] / $ratio_x;
                       $int_height = ($final_height / 2) - $mid_height;
                       imagecopyresampled($this->_current_thumb['img'],$this->_source['img'],0,-$int_height,0,0,$thumb_width,$final_height,$this->_source['sizes'][0],$this->_source['sizes'][1]);
                   }
                   else{
                       imagecopyresampled($this->_current_thumb['img'],$this->_source['img'],0,0,0,0,$thumb_width,$thumb_height,$this->_source['sizes'][0],$this->_source['sizes'][1]);
                   }
                   if(!is_null($filename)){
                       return $this->save($filename);
                   }
                   else{
                       return true; 
                   }
               }
               catch(Exception $e){
                   die($e->__toString().'. Impossible de retailler l\'image à partir des dimensions voulues : '.$thumb_width.' * '.$thumb_height);
               }
           }
     
           // Resize on width, automatic height resizing
     
           function resize_width($thumb_width, $filename = null){
               try {
                   $this->clear_current_thumb();
     
                   $ratio_x = $this->_source['sizes'][0] / $thumb_width;
                   $thumb_height = $this->_source['sizes'][1] / $ratio_x;
     
                   $this->_current_thumb['img'] = imagecreatetruecolor($thumb_width,$thumb_height);
                   $this->_current_thumb['sizes'][0] = $thumb_width;
                   $this->_current_thumb['sizes'][1] = $thumb_height;
     
                   imagecopyresampled($this->_current_thumb['img'],$this->_source['img'],0,0,0,0,$thumb_width,$thumb_height,$this->_source['sizes'][0],$this->_source['sizes'][1]);
                   if(!is_null($filename)){
                       return $this->save($filename);
                   }
                   else{
                       return true; 
                   }
               }
               catch(Exception $e){
                   die($e->__toString().'Impossible de redimensionner cette image à partir de cette largeur : '.$thumb_width);    
               }
           }
     
           // Resize on height, automatic width resizing
     
           function resize_height($thumb_height, $filename = null){
               try {
                   $this->clear_current_thumb();
     
                   $ratio_y = $this->_source['sizes'][1] / $thumb_height;
                   $thumb_width = $this->_source['sizes'][0] / $ratio_y;
     
                   $this->_current_thumb['img'] = imagecreatetruecolor($thumb_width,$thumb_height);
                   $this->_current_thumb['sizes'][0] = $thumb_width;
                   $this->_current_thumb['sizes'][1] = $thumb_height;
     
                   imagecopyresampled($this->_current_thumb['img'],$this->_source['img'],0,0,0,0,$thumb_width,$thumb_height,$this->_source['sizes'][0],$this->_source['sizes'][1]);
                   if(!is_null($filename)){
                       return $this->save($filename);
                   }
                   else{
                       return true; 
                   }
               }
               catch(Exception $e){
                   die($e->__toString().'Impossible de redimensionner cette image à partir de cette hauteur : '.$thumb_height); 
               }
           }
     
           // Save the current thumb into the save directory with the choosen filename
     
           function save($filename){
               $this->put_icon_if_needed();
               $this->put_text_if_needed();
               return $this->save_thumb_image($this->_current_thumb['img'], $this->_save_directory.$filename, $this->_thumbs_quality);
           }
     
           // Destroy the current thumb, the icon, the source image, and the text if not are nulls
     
           function clean(){
               @imagedestroy($this->_source['img']);
               unset($this->_source['img']);
               if(!is_null($this->_current_thumb)){
                   @imagedestroy($this->_current_thumb['img']);
                   unset($this->_current_thumb['img']);
                   $this->_current_thumb = null;    
               }
               if(!is_null($this->_icon)){
                   @imagedestroy($this->_icon['img']);
                   unset($this->_icon);
                   $this->_icon = null; 
               }
               if(!is_null($this->_text)){
                   @imagedestroy($this->_text['img']);
                   unset($this->_text);
                   $this->_text = null; 
               }    
           }
     
        // -----------------
        // PRIVATE FUNCTIONS
        // -----------------
     
           // create the source image
     
           private function build_image_from_path($path){
               try {
                  $type = $this->get_image_extension($path);
                  switch($type){
                      case 'gif':
                           return imagecreatefromgif($path); break;
                      case 'png':
                           return imagecreatefrompng($path); break;
                      case 'jpeg':
                      case 'jfif':
                      case 'jpg':
                      default :
                           return imagecreatefromjpeg($path); break;
                  }
               }
               catch (Exception $e){
                     die($e->__toString().'. Impossible de créer l\'image à partir de la source : <span style="color:red">'.$path.'</span>');
               }
           }
     
           // Save the thumb image to chosen quality
     
           private function save_thumb_image($thumb, $path, $quality){
               try {
                  $type = $this->get_image_extension($path);
                  switch($type){
                      case 'gif':
                           imagegif($thumb,$path); break;
                      case 'png':
                           imagepng($thumb,$path); break;
                      case 'jpeg':
                      case 'jpg':
                      case 'jfif':
                      default :
                           imagejpeg($thumb,$path,$quality); break;
                  }
               }
               catch (Exception $e){
                     die($e->toString().'. Impossible de créer la miniature à l\'endroit spécifié ou la librarie GD n\'est pas activée : <span style="color:red">'.$path.'</span>');
               }
     
           }
     
           // Put the icon on the current thumb if not is null, rebuild if has changed
     
           private function put_icon_if_needed(){
               if(!is_null($this->_icon)){
                   $left = 0;
                   $top = 0;
                   $right = $this->_current_thumb['sizes'][0] - $this->_icon['sizes'][0];
                   $bottom = $this->_current_thumb['sizes'][1] - $this->_icon['sizes'][1];
                   $center_left = $right / 2;
                   $center_top = $bottom / 2;
     
                   switch($this->_icon['position_left']){
                       case 'left' : $this->_icon['margin_left'] = $left; break;
                       case 'right' : $this->_icon['margin_left'] = $right; break;
                       case 'center' : $this->_icon['margin_left'] = $center_left; break;
                       default : $this->_icon['margin_left'] = 0; break;
                   }
     
                   switch($this->_icon['position_top']){
                       case 'top' : $this->_icon['margin_top'] = $top; break;
                       case 'bottom' : $this->_icon['margin_top'] = $bottom; break;
                       case 'center' : $this->_icon['margin_top'] = $center_top; break;
                       default : $this->_icon['margin_top'] = 0; break;
                   }
     
                   if(!isset($this->_icon['is_built']) || !$this->_icon['is_built']){
                       imagealphablending($this->_icon['img'],false);
                       $black = imagecolorallocate($this->_icon['img'],0,0,0);
                       imagefill($this->_icon['img'],0,0,$black);
                       imagecolortransparent($this->_icon['img'],$black);
                       $this->_icon['is_built'] = true;
                   }
     
                   $icon_width = $this->_icon['sizes'][0];
                   $icon_height = $this->_icon['sizes'][1];
     
                   imagecopymerge($this->_current_thumb['img'], $this->_icon['img'], $this->_icon['margin_left'], $this->_icon['margin_top'], 0, 0, $icon_width, $icon_height, $this->_icon['alpha']);
                   return true;
               }
               else{
                   return false;                
               }
           }
     
           // Put the text on the current thumb if not is null, rebuild if has changed
     
           private function put_text_if_needed(){
               if(!is_null($this->_text)){
                    if(!isset($this->_text['color']) || $this->_text['color'] == null){
                        $this->_text['color'] = Array(255,255,0);    
                    } 
     
                    $left = 0;
                    $top = 0;
                    $right = $this->_current_thumb['sizes'][0] - $this->_text['sizes'][0];
                    $bottom = $this->_current_thumb['sizes'][1] - $this->_text['sizes'][1];
                    $center_left = $right / 2;
                    $center_top = $bottom / 2;
     
                    switch($this->_text['position_left']){
                        case 'left' : $this->_text['margin_left'] = $left; break;
                        case 'right' : $this->_text['margin_left'] = $right; break;
                        case 'center' : $this->_text['margin_left'] = $center_left; break;
                        default : $this->_text['margin_left'] = 0; break;
                    }
     
                    switch($this->_text['position_top']){
                        case 'top' : $this->_text['margin_top'] = $top; break;
                        case 'bottom' : $this->_text['margin_top'] = $bottom; break;
                        case 'center' : $this->_text['margin_top'] = $center_top; break;
                        default : $this->_text['margin_top'] = 0; break;
                    }       
     
                    $color = imagecolorallocate($this->_current_thumb['img'], $this->_text['color'][0], $this->_text['color'][1], $this->_text['color'][2]);        
                    $shadow_grey = imagecolorallocate($this->_current_thumb['img'], 128, 128, 128);
     
                    if(is_int($this->_text['font'])){
                        if(isset($this->_text['shadow']) && $this->_text['shadow'] == true){
                            imagestring($this->_current_thumb['img'], $this->_text['font'], $this->_text['margin_left'] + 1, $this->_text['margin_top'] + 1, $this->_text['text'], $shadow_grey);       
                        }
                        imagestring($this->_current_thumb['img'], $this->_text['font'], $this->_text['margin_left'], $this->_text['margin_top'], $this->_text['text'], $color);
                    }
                    else{
                        if(isset($this->_text['shadow']) && $this->_text['shadow'] == true){
                            imagettftext($this->_current_thumb['img'], $this->_text['size'], 0, $this->_text['margin_left'] + 1, $this->_text['margin_top'] + 1, $shadow_grey, $font, $this->_text['text']);        
                        }
                        imagettftext($this->_current_thumb['img'], $this->_text['size'], 0, $this->_text['margin_left'], $this->_text['margin_top'], $color, $this->_text['font'], $this->_text['text']);           
                    }
     
                    return true;
               }
               else{
                   return false;    
               }            
           }
     
           // Calculate the new text width and height according to the font width and the number of chars
     
           private function reload_text_sizes(){
               $this->_text['sizes'][0] = imagefontwidth($this->_text['size']) * strlen($this->_text['text']);
               $this->_text['sizes'][1] = imagefontheight($this->_text['size']) * 1;    
           }
     
           // Delete the temporary thumb in memory
     
           private function clear_current_thumb(){
               if($this->_current_thumb != null){
                   @imagedestroy($this->_current_thumb['img']);
                   if(isset($this->_current_thumb)) $this->_current_thumb = null;
                   return is_null($this->_current_thumb);
               }
               else{
                return true;
               }
           }
     
    }
    ?>
    Voici comment utiliser cette classe à travers divers example, la fonction qui permet de recadrer est la fonction resize_crop(largeur, hauteur, optionnel:nomfichier) :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
     
    <html>
      <head>
        <style type="text/css">
            body {width:800px;margin:auto;}
            div {background:#eee;margin:0 10px 10px 0;float:left;}
        </style>
      </head>
      <body>
        <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
            <input type="file" name="source"/>
            <input type="submit" name="valid" value="Valid"/>
        </form>
     
        <?php
        require_once 'thumbsbuilder.class.php'; 
        if(isset($_FILES['source']['name'])){
            $source_image_extension = thumbs_builder::get_image_extension($_FILES['source']['name']);
            $source_image_path = 'images/background.'.$source_image_extension;
     
            if(move_uploaded_file($_FILES['source']['tmp_name'], $source_image_path)){
                $thumbs_saving_path = 'images/';
                $thumbs_image_quality = 95;
     
                $tb = new thumbs_builder($source_image_path, $thumbs_saving_path, $thumbs_image_quality);
     
                echo '<h1>Source image path : '.$tb->get_source_path().'</h1>';
                /* EXAMPLE 1 1 */
                $tb->resize_crop(70,70,'1.jpeg');
                echo '<div>RESIZE CROP <br/><img src="images/1.jpeg"/></div>';
     
                /* EXAMPLE 2 */
                $tb->resize_width(100,'2.jpeg');
                echo '<div>RESIZE ON WIDTH <br/><img src="images/2.jpeg"/></div>';
     
                /* EXAMPLE 3 */
                $tb->resize_height(250,'3.jpeg');
                echo '<div>RESIZE ON HEIGHT <br/><img src="images/3.jpeg"/></div>';
     
                /* EXAMPLE 4 */
                $tb->resize(200,50,"FFCC33",'4.jpeg');
                echo '<div>RESIZE NOCROP 1 <br/><img src="images/4.jpeg"/></div>';
     
                /* EXAMPLE 5 */
                $tb->resize(300,300,"a12");
                $tb->remove_icon();
                $tb->remove_text();
                $tb->save('5.jpeg');
                echo '<div>RESIZE NOCROP 2 <br/><img src="images/5.jpeg"/></div>';
     
                $tb->clean(); // clean memory usage     
            }
        } 
        ?>
      </body>
    </html>
    Dans cette exemple l'image est enregistrée sous le nom de background.* et génère 5 images jpeg, tu peux changer le type d'image générée simplement en changeant l'extension dans le nom de la miniature.

    À chaque appel d'une fonction resize_*, la miniature générée par le resize_* précédent est écrasée.

  8. #8
    Membre confirmé Avatar de kryogen
    Homme Profil pro
    Inscrit en
    Mars 2007
    Messages
    140
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Mars 2007
    Messages : 140
    Par défaut
    merci, cela marche bien. Mais en effet la transparence (chez moi) est assez foncée.
    Mais peut être avec les fonctions suivantes peux-tu améliorer la transparence (si j'avais ton niveau, je l'aurai bien fait moi même mais là je tâtonne dans le noir) :
    - imagecolorclosestalpha (Retourne la couleur la plus proche, en tenant compte du canal alpha)
    - imagecolorresolvealpha (Retourne un index de couleur ou son alternative la plus proche, y compris le canal alpha)
    - imagecolorexactalpha (Retourne l'index d'une couleur avec son canal alpha)
    merci en tout cas

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [ImageMagick] Recadrage d'image
    Par dtcSearch dans le forum Bibliothèques et frameworks
    Réponses: 0
    Dernier message: 30/04/2010, 17h07
  2. Algortihme recadrage d'images
    Par Padawansr dans le forum Traitement d'images
    Réponses: 2
    Dernier message: 27/01/2010, 15h19
  3. recadrage d'image pour comparaison
    Par youkoun dans le forum Traitement d'images
    Réponses: 9
    Dernier message: 25/08/2008, 09h29
  4. [Upload] Recadrage d'image en mode web
    Par bractar dans le forum Langage
    Réponses: 4
    Dernier message: 14/06/2007, 17h49
  5. Controle de recadrage d'image
    Par tostinni dans le forum VB 6 et antérieur
    Réponses: 5
    Dernier message: 09/11/2005, 23h50

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo