How to add a cover image like facebook or adjust the position of image?

In this tutorial, I am explaining how to add a cover image to a web page like on facebook. Here I am using Laravel framework to create a page where I can upload and adjust the image position like the Facebook cover image.

DEMO

HTML

Create a div with id="bgimage". Inside that I added the code to display cover image and in this image, added a upload file button which is customized with CSS. When click on this button it simply upload the image and hide this div,then display another div which help to change the position of image.

Complete HTML Code

<div id="bgimage" class="hovercover text-center">
<img class="img-responsive" style="margin-top: {{$image->position}};" src="{{asset('img').'/'.$image->image}}">

<div class="hover-div">
<form id="hoverform" action="{{url('/upload')}}" enctype="multipart/form-data" method="post">
{{ csrf_field() }} 
<label class="custom-file-upload" title="Change Cover Image" for="file-upload"> <i class="fa fa-file-image-o"></i> Change Cover </label> 
<input id="file-upload" name="file" type="file">
</form>
</div>
</div>
<div id="adjimage" class="hovercover1 text-center" style="display: none;"></div>

HTML CODE EXPLANATION

As I said earlier, I created a two div, first one to display and upload the cover image which has id="bgimage" and the other div to adjust the image after uploading the cover image which has id="adjimage".

Let’s look into the first div:-
First I am adding a img tag to display cover image

<img class="img-responsive" style="margin-top: {{$image->position}};" src="{{asset('img').'/'.$image->image}}">

the above code is so simple as given below

<img class="img-responsive" style="margin-top: 1px;" src="image/cover.jpg">

then I created one more div to hold the form to upload the image.

<div id="css">&nbsp;</div>
<div class="hover-div"><form id="hoverform" action="{{url('/upload')}}" enctype="multipart/form-data" method="post">{{ csrf_field() }} <label class="custom-file-upload" title="Change Cover Image" for="file-upload"> <i class="fa fa-file-image-o"></i>&nbsp; Change Cover </label> <input id="file-upload" name="file" type="file"></form></div>

here I customised the input button using CSS. This is a basic form which will upload the image.

CSS

Below are the CSS code.

Complete CSS Code

.hovercover{
    display:inline-block;
    position:relative;
    overflow: hidden;
}
.hovercover1{
    display:inline-block;
    position:relative;
    overflow: hidden;
}
.hover-div{
    position: absolute;
    right: 1%;
    bottom: 1%;
}

#file-upload{
    display: none;
}
.custom-file-upload {
    
    display: inline-block;
    padding: 6px 12px;
    background-color: #c74d4e;
    cursor: pointer;
    color :#fff;
     
}

#bgimage {
height: 300px;
position: relative;
overflow: hidden;
background-color:#ffffff;
}

#adjimage {
height: 300px;
width:100%;
position: relative;
overflow: hidden;
background-color:#ffffff;
}



#timelineBackground {
height: 300px;
position: relative;
overflow: hidden;
background-color:#ffffff;
}
#timelineShade {
min-height: 95px;
position: absolute;
margin-top: -95px;
width: 100%;
}
.timelineUploadBG {
position: absolute;
margin-top: 50px;
margin-left: 813px;
height: 32px;
width: 32px;
}

.uploadFile input {
filter: alpha(opacity=0);
opacity: 0;
margin-left: -110px;
}
.custom-file-input {
height: 25px;
cursor: pointer;
}
#timelineBGload{
position: relative;
overflow: hidden;
background-color:#ffffff;
}
.headerimage{
    cursor: move;
}
.btn-save-drag{
    position: absolute;
    
    right: 1%;
    bottom: 1%;
}

Above CSS code helps to hide usual file upload button.

file upload

Jquery

Jquery will upload/submit the image soon after you select the image, and it helps to adjust the image position after uploading.
Download the js librery from here

Complete Jquery Code

<script type="text/javascript" src="{{asset('js/jquery-ui.min.js')}}"></script>
<script type="text/javascript" src="{{asset('js/jquery.wallform.js')}}"></script>
<script type="text/javascript" src="{{asset('js/jwincrop.js')}}"></script>
<script type="text/javascript">
 

     // submit the form soon after change image
     $('#file-upload').on('change',function(){
        
        $("#hoverform").ajaxForm({target: '#adjimage',
            success:function(){
            $(".hover-div").hide();
                
                $("#bgimage").hide();
                $("#adjimage").show();
                
                
            }}).submit();
     });
    
   
     
  $('.hovercove').each(function() {
    //set size
    var th = $(this).height(),//box height
        tw = $(this).width(),//box width
        im = $(this).children('img'),//image
        ih = im.height(),//inital image height
        iw = im.width();//initial image width
    if (ih>iw) {//if portrait
        im.addClass('ww').removeClass('wh');//set width 100%
    } else {//if landscape
        im.addClass('wh').removeClass('ww');//set height 100%
    }
    //set offset
    var nh = im.height(),//new image height
        nw = im.width(),//new image width
        hd = (nh-th)/2,//half dif img/box height
        wd = (nw-tw)/2;//half dif img/box width
    if (nh<nw) {//if portrait
        im.css({marginLeft: '-'+wd+'px', marginTop: 0});//offset left
    } else {//if landscape
        im.css({marginTop: '-'+hd+'px', marginLeft: 0});//offset top
    }
});


</script>

JQUERY CODE EXPLANATION

Our first job is to add the library files ( You can download those files from here ).

<script type="text/javascript" src="{{asset('js/jquery-ui.min.js')}}"></script>
<script type="text/javascript" src="{{asset('js/jquery.wallform.js')}}"></script>
<script type="text/javascript" src="{{asset('js/jwincrop.js')}}"></script>

Then I added a on change function, it will submit the form and hide the uploading div and display the image adjusting div.

$("#hoverform").ajaxForm({target: '#adjimage',
            success:function(){
            $(".hover-div").hide();
                $("#bgimage").hide();
                $("#adjimage").show();
              }}).submit();
     });

Next, I added a each function to change the postion of image and I commented what the each line is for.

$('.hovercove').each(function() {
    //set size
    var th = $(this).height(),//box height
        tw = $(this).width(),//box width
        im = $(this).children('img'),//image
        ih = im.height(),//inital image height
        iw = im.width();//initial image width
    if (ih>iw) {//if portrait
        im.addClass('ww').removeClass('wh');//set width 100%
    } else {//if landscape
        im.addClass('wh').removeClass('ww');//set height 100%
    }
    //set offset
    var nh = im.height(),//new image height
        nw = im.width(),//new image width
        hd = (nh-th)/2,//half dif img/box height
        wd = (nw-tw)/2;//half dif img/box width
    if (nh<nw) {//if portrait
        im.css({marginLeft: '-'+wd+'px', marginTop: 0});//offset left
    } else {//if landscape
        im.css({marginTop: '-'+hd+'px', marginLeft: 0});//offset top
    }
});

PHP

As I said earlier, I used Laravel framework. First I am creating a database ( You can use Model Migration also), Here I directly created the database in PHPMyAdmin, let’s call it as images.
DB contains:-

  • id(int)-primary key and autoincrement.
  • image(varchar).
  • position(varchar)
  • created_at(DateTime).
  • updated_at(DateTime).

then, create image model using artisan command.

php artisan make:model Image

create a controller using artisan.

php artisan make:controller ImageprocessController

I need to add three functions in controller,

  • To view the cover Image
  • To upload the image
  • To update the position

View Cover image

public function upload()
    {
     $image=Image::select('image','position')->first();
      return view('img.adjust')->with('image',$image);
    }

Upload funtion

public function postupload(Request $request)
    {
     
      $file         = $request->file('file');
      $rules = array('file' => 'required|mimes:png,gif,jpeg,jpg'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
      $validator = Validator::make(array('file'=> $file), $rules);
      if($validator->passes()){
                
                 $image = $file->move( 'img', sprintf('%s-%s.%s', time(), str_random(), explode('/', $file->getMimeType())[1]));
                    $img            = Image::where('id','=',1)->first();
                   
                    $img->image     = $image->getFilename();
                    $img->save();

                    
                    $bgSave='<img id="timelineBGload" class="headerimage ui-corner-all " style="top: 0px; width: 100%;" src="'.\App::make('url')->to('/'). '/img/'.$image->getFilename().'">';
                    $bgSave .="<div class="btn-save-drag">
<p style="background-color: white; font-size: 0.8em;">Drag and adjust the image</p>
<button class="bgSave btn btn-info bg-lg">Save</button></div>
";
                    $bgSave .= "<script>$('.headerimage').on('mouseover',function()
                      {

                        var y1 = $('#adjimage').height();
                        var y2 =  $('.headerimage').height();

                        $(this).draggable({

                          scroll: false,
                          axis: 'y',
                          drag: function(event, ui) {
                            if(ui.position.top >= 0)
                            {
                            ui.position.top = 0;
                            }
                            else if(ui.position.top <= y1 - y2)
                            {
                            ui.position.top = y1 - y2;
                            }
                        },
                        stop: function(event, ui)
                        {
                        }
                      });
                      });
                      $('.bgSave').on('click',function ()
                          {
                            var p = $('#timelineBGload').attr('style');
                            var Y =p.split('top:');
                            var Z=Y[1].split(';');
                            var dataString ='position='+Z[0];
                            $.ajax({
                              type: 'POST',
                              url: '";
                             $bgSave .= url('/cover-image-save');
                             $bgSave .="',
                              data: dataString,
                              cache: false,
                               headers: {
                                'X-CSRF-TOKEN': '". csrf_token() ."'
                                },
                              success: function(html)
                              {
                                if(html)
                                {
                                   location.reload(); 
                                 
                                  return false;
                                }
                              }
                            });
                          return false;
                          });
                      

                      </script>";
                    return $bgSave;


      }
    }

Image Adjusting funtion

public function postimgAdjustpostion(Request $request)
    {

      $usr            = Image::where('id','=',1)->first();
      $usr->position  = $request->get('position');
      $usr->save();
      return redirect()->back();
    }

Complete controller code

<!--?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use Validator;
use App\Image;
class ImageprocessController extends Controller
{
  public function upload()
    {
     $image=Image::select('image','position')--->first();
      return view('img.adjust')->with('image',$image);
    }

  public function postupload(Request $request)
    {
     
      $file         = $request->file('file');
      $rules = array('file' => 'required|mimes:png,gif,jpeg,jpg'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
      $validator = Validator::make(array('file'=> $file), $rules);
      if($validator->passes()){
                
                 $image = $file->move( 'img', sprintf('%s-%s.%s', time(), str_random(), explode('/', $file->getMimeType())[1]));
                    $img            = Image::where('id','=',1)->first();
                   
                    $img->image     = $image->getFilename();
                    $img->save();

                    
                    $bgSave='<img id="timelineBGload" class="headerimage ui-corner-all " style="top: 0px; width: 100%;" src="'.\App::make('url')->to('/'). '/img/'.$image->getFilename().'">';
                    $bgSave .="<div class="btn-save-drag">
<p style="background-color: white; font-size: 0.8em;">Drag and adjust the image</p>
<button class="bgSave btn btn-info bg-lg">Save</button></div>
";
                    $bgSave .= "<script>$('.headerimage').on('mouseover',function()
                      {

                        var y1 = $('#adjimage').height();
                        var y2 =  $('.headerimage').height();

                        $(this).draggable({

                          scroll: false,
                          axis: 'y',
                          drag: function(event, ui) {
                            if(ui.position.top >= 0)
                            {
                            ui.position.top = 0;
                            }
                            else if(ui.position.top <= y1 - y2)
                            {
                            ui.position.top = y1 - y2;
                            }
                        },
                        stop: function(event, ui)
                        {
                        }
                      });
                      });
                      $('.bgSave').on('click',function ()
                          {
                            var p = $('#timelineBGload').attr('style');
                            var Y =p.split('top:');
                            var Z=Y[1].split(';');
                            var dataString ='position='+Z[0];
                            $.ajax({
                              type: 'POST',
                              url: '";
                             $bgSave .= url('/cover-image-save');
                             $bgSave .="',
                              data: dataString,
                              cache: false,
                               headers: {
                                'X-CSRF-TOKEN': '". csrf_token() ."'
                                },
                              success: function(html)
                              {
                                if(html)
                                {
                                   location.reload(); 
                                 
                                  return false;
                                }
                              }
                            });
                          return false;
                          });
                      

                      </script>";
                    return $bgSave;


      }
    }
   
    public function postimgAdjustpostion(Request $request)
    {

      $usr            = Image::where('id','=',1)->first();
      $usr->position  = $request->get('position');
      $usr->save();
      return redirect()->back();
    }
}

Now i gonna add route to this

Route::get('/upload', 'ImageprocessController@upload');
Route::post('/upload', 'ImageprocessController@postupload');
Route::post('/cover-image-save', 'ImageprocessController@postimgAdjustpostion');