Search code examples
laravelintervention

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


Solution

  • 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');
    });