PHP GD library used to merge two images

前端 未结 3 1893
耶瑟儿~
耶瑟儿~ 2021-01-27 22:58

Okay, so I have two images in a file. One of them is of a t-shirt. The other is of a logo. I used CSS to style the two images so that it looks like the logo is written on the t-

相关标签:
3条回答
  • 2021-01-27 23:17

    It's possible. Sample code:

    // or whatever format you want to create from
    $shirt = imagecreatefrompng("shirt.png"); 
    
    // the logo image
    $logo = imagecreatefrompng("logo.png"); 
    
    // You need a transparent color, so it will blend nicely into the shirt.
    // In this case, we are selecting the first pixel of the logo image (0,0) and
    // using its color to define the transparent color
    // If you have a well defined transparent color, like black, you have to
    // pass a color created with imagecolorallocate. Example:
    // imagecolortransparent($logo, imagecolorallocate($logo, 0, 0, 0));
    imagecolortransparent($logo, imagecolorat($logo, 0, 0));
    
    // Copy the logo into the shirt image
    $logo_x = imagesx($logo); 
    $logo_y = imagesy($logo); 
    imagecopymerge($shirt, $logo, 0, 0, 0, 0, $logo_x, $logo_y, 100); 
    
    // $shirt is now the combined image
    // $shirt => shirt + logo
    
    
    //to print the image on browser
    header('Content-Type: image/png');
    imagepng($shirt);
    

    If you don't want to specify a transparent color, but instead want to use an alpha channel, you have to use imagecopy instead of imagecopymerge. Like this:

    // Load the stamp and the photo to apply the watermark to
    $logo = imagecreatefrompng("logo.png");
    $shirt = imagecreatefrompng("shirt.png");
    
    // Get the height/width of the logo image
    $logo_x = imagesx($logo); 
    $logo_y = imagesy($logo);
    
    // Copy the logo to our shirt
    // If you want to position it more accurately, check the imagecopy documentation
    imagecopy($shirt, $logo, 0, 0, 0, 0, $logo_x, $logo_y);
    

    References:
    imagecreatefrompng
    imagecolortransparent
    imagesx
    imagesy
    imagecopymerge
    imagecopy

    Tutorial from PHP.net to watermark images
    Tutorial from PHP.net to watermark images (using an alpha channel)

    0 讨论(0)
  • 2021-01-27 23:17

    This tutorial should get you started http://www.php.net/manual/en/image.examples.merged-watermark.php and on the right track

    0 讨论(0)
  • 2021-01-27 23:22

    Yes.

    http://php.net/manual/en/book.image.php

    0 讨论(0)
提交回复
热议问题