shekwo
shekwo

Reputation: 1447

Adding watermark to images in Laravel

I am trying to add a text (as watermark) to images. I am using Image/Intervention package. The text shows but I want it to be at top right hand corner of the image and I also want the size increased. The text is currently at top-left corner and the size is extremely small.

This is my code

if($request->hasFile('file')) {
    foreach ($request->file('file') as $photo) {
        $file = $photo;
        $img = Image::make($file);
        $img->text('12345 ', 120, 100, function($font) {
            $font->size(45);
            $font->color('#e1e1e1');
            $font->align('center');
            $font->valign('top');
        });
        $img->save(public_path('images/hardik3.jpg'));
    }
}

How do I solve this?

enter image description here

Upvotes: 0

Views: 2512

Answers (2)

mdexp
mdexp

Reputation: 3567

From the documentation:

Font sizing is only available if a font file is set and will be ignored otherwise. Default: 12

So you have to specify a custom font just like in the below example:

$img->text('foo', 0, 0, function($font) {
    $font->file('foo/bar.ttf');
    $font->size(24);
    $font->color('#fdf6e3');
    $font->align('center');
    $font->valign('top');
    $font->angle(45);
});

Update

The text alignment is relative to the size of the textbox, but the positioning is given by the x and y coordinates (2nd and 3rd parameters of the text method). To put the text on the right top corner you can do:

$img->text('foo', $img->width(), 100, function($font) {
    $font->file('foo/bar.ttf');
    $font->size(24);
    $font->color('#e1e1e1');
    $font->align('right');
    $font->valign('top');
});

Upvotes: 2

Augusto Moura
Augusto Moura

Reputation: 1392

The text function accepts the X and Y coordinates of the position to insert the text. The text is being printed into the shown position because you used the coordinates 120 and 100.

Try the following:

if($request->hasFile('file')) {
    foreach ($request->file('file') as $photo) {
        $file = $photo;
        $img = Image::make($file);
        $img->text('12345 ', $img->width() - 120, 100, function($font) {
            $font->size(45);
            $font->color('#e1e1e1');
            $font->align('center');
            $font->valign('top');
        });
        $img->save(public_path('images/hardik3.jpg'));
    }
}

Source: http://image.intervention.io/api/text

Upvotes: 1

Related Questions