imagecopymerge() function in PHP

The imagecopymerge() function copies and merges part of one image onto another with specified transparency. This function is useful for creating watermarks, overlays, or blending images together.

Syntax

imagecopymerge(dst_img, src_img, dst_x, dst_y, src_x, src_y, src_w, src_h, pct)

Parameters

  • dst_img − Destination image resource

  • src_img − Source image resource

  • dst_x − X-coordinate of destination point

  • dst_y − Y-coordinate of destination point

  • src_x − X-coordinate of source point

  • src_y − Y-coordinate of source point

  • src_w − Source width in pixels

  • src_h − Source height in pixels

  • pct − Transparency percentage (0-100). 0 = transparent, 100 = opaque

Return Value

Returns TRUE on success or FALSE on failure.

Example 1: Basic Image Merging

Here's how to merge two images with 60% opacity ?

<?php
    // Create destination and source images
    $destImg = imagecreatefrompng('/images/Javascript.png');
    $srcImg = imagecreatefrompng('/images/java8.png');
    
    // Merge images: place source at (10,10) with 60% opacity
    imagecopymerge($destImg, $srcImg, 10, 10, 0, 0, 350, 120, 60);
    
    // Output merged image
    header('Content-Type: image/png');
    imagepng($destImg);
    
    // Clean up memory
    imagedestroy($destImg);
    imagedestroy($srcImg);
?>

Example 2: Different Coordinates and Opacity

This example demonstrates merging with different positioning and 80% opacity ?

<?php
    $destImg = imagecreatefrompng('/images/php.png');
    $srcImg = imagecreatefrompng('/images/Operating-System.png');
    
    // Merge at position (10,20) with 80% opacity
    imagecopymerge($destImg, $srcImg, 10, 20, 0, 0, 390, 100, 80);
    
    header('Content-Type: image/png');
    imagepng($destImg);
    
    imagedestroy($destImg);
    imagedestroy($srcImg);
?>

Key Points

  • Percentage value controls transparency: 0% = fully transparent, 100% = fully opaque

  • Source coordinates specify which part of the source image to copy

  • Destination coordinates specify where to place the copied portion

  • Always destroy image resources to free memory

Conclusion

The imagecopymerge() function is essential for creating image overlays and watermarks in PHP. Use the percentage parameter to control transparency and achieve the desired blending effect.

Updated on: 2026-03-15T08:05:35+05:30

852 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements