Search code examples
phpwatermark

Watermark on image not working on all images


I have code where place a watermark on the image. Watermark not working for all images and I don't know why. On images where not working slowly load the page and show special characters like this

�PNG  IHDR��E pHYs�e� IDATx��Y�$;�&� �="Β�]�VW/3�3��L�1�Lң����4�c�����ꪺKf�s"��Iz`��������Z��ca~|!A ���?

Here is my code

<div class="row">
    <?php foreach ($images as $image) {
    ?>
        <div class="col-md-3 mb-4">
            <?php if ($photo_service == '1') { ?>
                <img src="./uploads/<?php echo $image['file_name']; ?>" alt="<?= $new['title'] ?>">
                <a class="btn btn-primary btn-xs mt-1" href="./uploads/<?php echo $image['file_name']; ?>" download><i class="fas fa-download me-2"></i>Preuzmi </a>
            <?php } else {

                // Load the stamp and the photo to apply the watermark to
                $folder = "./uploads/";
                $file = $image['file_name'];
                $stamp = imagecreatefrompng('./assets/images/watermark.png');
                $im = imagecreatefromjpeg($folder . $file);

                //Set the margins for the stamp and get the height/width of the stamp image
                $marge_right = 0;
                $marge_bottom = 0;
                $sx = imagesx($stamp);
                $sy = imagesy($stamp);

                // Copy the stamp image onto our photo using the margin offsets and the photo 
                // width to calculate positioning of the stamp.

                imagecopy($im, $stamp, (imagesx($im) - $sx - $marge_right) / 2, (imagesy($im) - $sy - $marge_bottom) / 2, 0, 0, imagesx($stamp), imagesy($stamp));

                //Output and free memory
                ob_start();
                imagepng($im);
                $img = ob_get_clean();
                ob_end_clean();
                imagedestroy($im);

                echo '<img src="data:image/x-icon;base64,' . base64_encode($img) . '">';

            ?>

            <?php } ?>

        </div>
    <?php

    }
    ?>
</div>

All images are in jpg or jpeg format


Solution

  • Solved, changed imagepng($im); to imagejpeg($im); I don't know why but this works