lemoney
lemoney

Reputation: 161

PHP make PNG 50% transparent

I want to take a PNG file and make it 50% transparent. How can I do that in PHP? I want to use it as a watermark and I can already get it on the image but now I need to make the watermark transparent.

Upvotes: 0

Views: 340

Answers (2)

mister martin
mister martin

Reputation: 6252

With PHP, you can do this using Imagick by creating a mask. The example below is from this tutorial.

<?php
// Create objects
$image = new Imagick('image.png');
$watermark = new Imagick();
$mask = new Imagick();
$draw = new ImagickDraw();

// Define dimensions
$width = $image->getImageWidth();
$height = $image->getImageHeight();

// Create some palettes
$watermark->newImage($width, $height, new ImagickPixel('grey30'));
$mask->newImage($width, $height, new ImagickPixel('black'));

// Watermark text
$text = 'Copyright';

// Set font properties
$draw->setFont('Arial');
$draw->setFontSize(20);
$draw->setFillColor('grey70');

// Position text at the bottom right of the image
$draw->setGravity(Imagick::GRAVITY_SOUTHEAST);

// Draw text on the watermark palette
$watermark->annotateImage($draw, 10, 12, 0, $text);

// Draw text on the mask palette
$draw->setFillColor('white');
$mask->annotateImage($draw, 11, 13, 0, $text);
$mask->annotateImage($draw, 10, 12, 0, $text);
$draw->setFillColor('black');
$mask->annotateImage($draw, 9, 11, 0, $text);

// This is needed for the mask to work
$mask->setImageMatte(false);

// Apply mask to watermark
$watermark->compositeImage($mask, Imagick::COMPOSITE_COPYOPACITY, 0, 0);

// Overlay watermark on image
$image->compositeImage($watermark, Imagick::COMPOSITE_DISSOLVE, 0, 0);

// Set output image format
$image->setImageFormat('png');

// Output the new image
header('Content-type: image/png');
echo $image;

Upvotes: 1

thenashone
thenashone

Reputation: 249

Apply a class to the image

<style>
.opacity-50 {
  opacity: 0.5;
  filter: alpha(opacity=50);
}
</style>

<img  class="opacity-50" src="filename.png">

Upvotes: 1

Related Questions