Wednesday, 3 February 2016

Croping Image (Crop Js with rails)

1. Add Crop js and lightbox js to your assets.

crop.js
"use strict";var cropbox=function(e){var t=document.querySelector(e.imageBox),n={state:{},ratio:1,options:e,imageBox:t,thumbBox:t.querySelector(e.thumbBox),spinner:t.querySelector(e.spinner),image:new Image,getDataURL:function(){var e=this.thumbBox.clientWidth,n=this.thumbBox.clientHeight,a=document.createElement("canvas"),i=t.style.backgroundPosition.split(" "),o=t.style.backgroundSize.split(" "),r=parseInt(i[0])-t.clientWidth/2+e/2,s=parseInt(i[1])-t.clientHeight/2+n/2,c=parseInt(o[0]),u=parseInt(o[1]),d=parseInt(this.image.height),l=parseInt(this.image.width);a.width=e,a.height=n;var g=a.getContext("2d");g.drawImage(this.image,0,0,l,d,r,s,c,u);var m=a.toDataURL("image/png");return m},getBlob:function(){for(var e=this.getDataURL(),t=e.replace("data:image/png;base64,",""),n=atob(t),a=[],i=0;i<n.length;i++)a.push(n.charCodeAt(i));return new Blob([new Uint8Array(a)],{type:"image/png"})},zoomIn:function(){this.ratio*=1.1,r()},zoomOut:function(){this.ratio*=.9,r()}},a=function(e,t,n){e.attachEvent?e.attachEvent("on"+t,n):e.addEventListener&&e.addEventListener(t,n)},i=function(e,t,n){e.detachEvent?e.detachEvent("on"+t,n):e.removeEventListener&&e.removeEventListener(t,render)},o=function(e){window.event?e.cancelBubble=!0:e.stopImmediatePropagation()},r=function(){var e=parseInt(n.image.width)*n.ratio,a=parseInt(n.image.height)*n.ratio,i=(t.clientWidth-e)/2,o=(t.clientHeight-a)/2;t.setAttribute("style","background-image: url("+n.image.src+"); background-size: "+e+"px "+a+"px; background-position: "+i+"px "+o+"px; background-repeat: no-repeat")},s=function(e){o(e),n.state.dragable=!0,n.state.mouseX=e.clientX,n.state.mouseY=e.clientY},c=function(e){if(o(e),n.state.dragable){var a=e.clientX-n.state.mouseX,i=e.clientY-n.state.mouseY,r=t.style.backgroundPosition.split(" "),s=a+parseInt(r[0]),c=i+parseInt(r[1]);t.style.backgroundPosition=s+"px "+c+"px",n.state.mouseX=e.clientX,n.state.mouseY=e.clientY}},u=function(e){o(e),n.state.dragable=!1},d=function(e){var t=window.event||e,a=t.detail?-120*t.detail:t.wheelDelta;n.ratio*=a>-120?1.1:.9,r()};return n.spinner.style.display="block",n.image.onload=function(){n.spinner.style.display="none",r(),a(t,"mousedown",s),a(t,"mousemove",c),a(document.body,"mouseup",u);var e=/Firefox/i.test(navigator.userAgent)?"DOMMouseScroll":"mousewheel";a(t,e,d)},n.image.src=e.imgSrc,a(t,"DOMNodeRemoved",function(){i(document.body,"DOMNodeRemoved",u)}),n};

lightbox.js
If you are using bootstrap then no need to add separately. otherwise add .

2. Html code
<div class="uploadBoxOuter font14">       
        <a href="javascript:void(0);"  onclick="$('.post_image').click();">
          <% if obj.try(:upload).try(:image).present? %>
            <%= image_tag obj.upload.image_url, id: 'imgprvw' %>
          <% else %>
            <img src="/assets/images/cemera.png" alt="" id='imgprvw'>
          <% end %>
        </a>

        <div class="error img_error"></div>
        <%= hidden_field_tag "image_url", false%>
        <%= hidden_field_tag "file_url", false%>
        <%= hidden_field_tag "cropped", false%>
        <%= u.file_field :image, :value=>u.object.image.url, class: "post post_image profile_picture", style: "visibility: hidden; width: 1px; height: 1px" ,:onchange => "showimagepreview(this)" %>
        <div class="grayBig mt20 bold">
          Add an image to bring your post to life
        </div>
        Images that are at least 700 x 400 pixels look best.
      </div>

  <a href="#" data-toggle="modal" data-target="#lightbox" style="display:none"></a>

  <div id="lightbox" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <button type="button" class="close hidden" data-dismiss="modal" aria-hidden="true">×</button>
      <div class="modal-content">
        <div class="modal-body">
          <div class="imageBox">
            <div class="thumbBox"></div>
            <div class="spinner" style="display: none">Loading...</div>
          </div>
          <div class="action crop">
            <input type="button" id="btnCropDone" value="CropDone" style="float: right">
            <input type="button" id="btnCrop" value="Crop" style="float: right">
            <input type="button" id="btnZoomIn" value="+" style="float: right">
            <input type="button" id="btnZoomOut" value="-" style="float: right">
          </div>
          <div class="cropped"></div>
        </div>
      </div>
    </div>
  </div>

3. Create new custome Js and drop below code
function showfilepreview(input) {
    if (!window.FileReader) {
      alert('This browser does not support the FileReader API.');
    }
    extension = input.files[0].name.substring( input.files[0].name.lastIndexOf('.') + 1).toLowerCase();
    if ( extension == "pdf" || extension == "doc" || extension == "docx" ) {
        $(".file_name").removeClass("error_file");
        $(".file_name").html("");
      if (input.files && input.files[0]) {
        if (input.files[0].size > 5000000) {
          $(".file_name").html("File should not be larger than 5 MB.").addClass("error_file");
          return false
        }
        var filerdr = new FileReader();
        var filename = input.files[0].name
        filerdr.onload = function(e) {
        if ( extension == "pdf" ){
          $('#fleprvw').attr('src', "../assets/images/pdf.png");
        }

        if ( extension == "doc" || extension == "docx" ){
          $('#fleprvw').attr('src', "../assets/images/docs.png");
        }

        $("#file_url").val(false);
        $( ".file_name" ).html( filename );
      }
      filerdr.readAsDataURL(input.files[0]);
      $('.remove_file').show();
      }
    } else {
      $(".file_name").html("Please add only pdf, doc, docx document.").addClass("error_file");
      return false;
    }
  }
  $(document).on("click", ".remove_image", function() {
    // $(".post_image").val('');
    // $("#post_upload_attributes_image").replaceWith($('<input id="post_upload_attributes_image" class="post post_image" type="file" name="post[upload_attributes][image]" onchange="showimagepreview(this)" style="visibility: hidden; width: 1px; height: 1px">'));
    $(".post.post_image.profile_picture").val('');
    $("#image_url").val(true);
    $('#imgprvw').attr('src', '/assets/images/cemera.png');
    $('.remove_image').hide();
  });


$(document).ready(function() {
  var $lightbox = $('#lightbox');
 
  $('[data-target="#lightbox"]').on('click', function(event) {
      var $img = $(this).find('img'),
         src = $img.attr('src'),
          alt = $img.attr('alt'),
          css = {
              'maxWidth': $(window).width() - 100,
              'maxHeight': $(window).height() - 100
          };
 
      $lightbox.find('.close').addClass('hidden');
      $lightbox.find('img').attr('src', src);
      $lightbox.find('img').attr('alt', alt);
      $lightbox.find('img').css(css);
  });
 
  $lightbox.on('shown.bs.modal', function (e) {
      var $img = $lightbox.find('img');
         
      $lightbox.find('.modal-dialog').css({'width': $img.width()});
      $lightbox.find('.close').removeClass('hidden');
  });
});


Thanks,
Hemant

No comments:

Post a Comment