Friday, June 28, 2019

Crop and Resize Images Using (Mouse Or Touch Capable) With This Simple jQuery Plugin

The Cropper plugin requires a copy of jQuery and it comes with two files: a CSS stylesheet and the JavaScript plugin library. Just add these files to your page and it should be good to go!
Download plugin file from here
var options = {
  aspectRatio: 0,
  preview: '.img-preview',
  ready: function (e) {
    console.log(e.type);
  },
  cropstart: function (e) {
    console.log(e.type, e.detail.action);
  },
  cropmove: function (e) {
    console.log(e.type, e.detail.action);
  },
  cropend: function (e) {
    console.log(e.type, e.detail.action);
  },
  crop: function (e) {
    var data = e.detail;

    console.log(e.type);
    data.x = Math.round(data.x);
    data.y = Math.round(data.y);
    data.height = Math.round(data.height);
    data.width = Math.round(data.width);
    data.rotate = typeof data.rotate !== 'undefined' ? data.rotate : '';
    data.scaleX = typeof data.scaleX !== 'undefined' ? data.scaleX : '';
    data.scaleY = typeof data.scaleY !== 'undefined' ? data.scaleY : '';

    console.log(data);
  },
  zoom: function (e) {
    console.log(e.type, e.detail.ratio);
  }
};
var cropper = new Cropper(image, options);

Monday, June 17, 2019

JavaScript | JQuery | Check if a variable is type of String | Number | Null | Undefined | Array | Object

console.log(Object.prototype.toString.call("This is string"));
console.log(Object.prototype.toString.call(undefined));
console.log(Object.prototype.toString.call(0));
console.log(Object.prototype.toString.call(null));
console.log(Object.prototype.toString.call([]));
console.log(Object.prototype.toString.call({}));
And respective output is as below:
[object String]
[object Undefined]
[object Number]
[object Null]
[object Array]
[object Object]

Saturday, May 25, 2019

jQuery convert PDF to Images Page by Page using pdfjsLib from Mozilla Foundation

First download pdf.js and pdf.workder.js from here or use direct link //mozilla.github.io/pdf.js/build/pdf.js and //mozilla.github.io/pdf.js/build/pdf.worker.js.

<script src="pdf.js"></script>

<title>PDF.js 'Hello, world!' example</title>

<h1>PDF.js 'Hello, world!' example</h1>

<canvas id="the-canvas" style="border:1px solid red;"></canvas>

<script type="text/javascript">
  var url = './sample2.pdf';

  // Loaded via <script> tag, create shortcut to access PDF.js exports.
  var pdfjsLib = window['pdfjs-dist/build/pdf'];

  // The workerSrc property shall be specified.
  pdfjsLib.GlobalWorkerOptions.workerSrc = 'pdf.worker.js';

  // Asynchronous download of PDF
  var loadingTask = pdfjsLib.getDocument(url);
  loadingTask.promise.then(function(pdf) {
    console.log('PDF loaded, total pages = ' + pdf.numPages);

    // Fetch the first page
    var pageNumber = 1;
    pdf.getPage(pageNumber).then(function(page) {
      console.log('Page loaded');

      var scale = 1.5;
      var viewport = page.getViewport({scale: scale});

      // Prepare canvas using PDF page dimensions
      var canvas = document.getElementById('the-canvas');
      var context = canvas.getContext('2d');
      canvas.height = viewport.height;
      canvas.width = viewport.width;

      // Render PDF page into canvas context
      var renderContext = {
        canvasContext: context,
        viewport: viewport
      };
      var renderTask = page.render(renderContext);
      renderTask.promise.then(function () {
        console.log('Page rendered');
      });
    });
  }, function (reason) {
    // PDF loading error
    console.error(reason);
  });
</script>

jQuery Resize and Compress Image

This is a jQuery technique to resize image using canvas and Image object. You can resize image as you wanted.
Below is a jQuery class that will actually convert file to blob after resize done:
class ImageResizer {
  "use strict"

  static _initDone = false;

  static resize(file, options, callback) {
    this._init();

    var thisOptions = {
      maxWidth: 1200
    };
    $.extend( thisOptions, options );

    var width = thisOptions.maxWidth;
    var fileName = file.name;
    var fileType = file.type;

    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(event) {
      const img = new Image();
      img.src = event.target.result;
      img.onload = function() {
        if (width > img.width) {
          width = img.width;
        }
        const elem = document.createElement('canvas');
        elem.width = width;
        const scaleFactor = width / img.width;
        elem.height = img.height * scaleFactor;
        const ctx = elem.getContext('2d');
        // img.width and img.height will contain the original dimensions
        ctx.drawImage(img, 0, 0, width, img.height * scaleFactor);

        // function(callback_function, file_type, quality_0_to_1)
        ctx.canvas.toBlob(function(blob) {
          blob.lastModifiedDate = Date.now();
          blob.name = fileName;
          blob.width = width;
          blob.height = img.height * scaleFactor;

          callback(undefined, blob);
        }, fileType, 1);
      },
        reader.onerror = function(error) {
          callback(error);
        };
    };
  }

  static _init() {
    if (!this._initDone) {
      this._initDone = true;

      if (!HTMLCanvasElement.prototype.toBlob) {
        Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
          value: function (callback, type, quality) {
            var dataURL = this.toDataURL(type, quality).split(',')[1];
            setTimeout(function() {
              var binStr = atob( dataURL ), len = binStr.length, arr = new Uint8Array(len);
              for (var i = 0; i < len; i++ ) {
                arr[i] = binStr.charCodeAt(i);
              }
              callback( new Blob( [arr], {type: type || 'image/png'} ) );
            });
          }
        });
      }
    }
  }
}
And you can use this from html page as below:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Image Resize Component</title>
  <script src="//code.jquery.com/jquery-1.7.2.min.js"></script>
  <script src="image-resizer.js"></script>
  <script type="text/javascript">
    $(document).on('ready', function() {
      var image = $("#PhotoPicker");
      image.on('change', function(e) {
        $("canvas").remove();

        ImageResizer.resize(e.target.files[0], {maxWidth: 300}, function(error, blob) {
          const canvas = document.createElement('canvas');
          canvas.width = blob.width
          canvas.height = blob.height;
          const context = canvas.getContext('2d');

          var img = new Image();
          img.onload = function(){
            context.drawImage(img, 0, 0, blob.width, blob.height);
          };
          img.onerror = function(e){
            console.log('Error during loading image:', e);
          };
          img.src = URL.createObjectURL(blob);

          document.body.appendChild(canvas);
        });
      });
    });
  </script>
</head>
<body>
<input type="file" id="PhotoPicker" accept="image/*" capture="camera"><br/><br/>
</body>
</html>

How to deal with big numbers in javascript | Extremely large numbers in javascript | Large Number Addition in JavaScript | How to deal with extremly big numbers in javascript |

Javascript supports at most 53 bit integers. What this means is that integers larger than 53 bits lose precision. This article will explain how to handle addition with integers larger than 53 bits in javascript.
I'm looking for a Mathematical solution that deals with really (long, big, huge, storms) numbers. I haven't found anything yet, But I don't wanna think that this problem hasn't be solve at this time. I'm looking for an easy Number solution, like Microsoft Excel Precision (30 decimals), or a BigInteger (Java) solution. in Javascript of course.
JavaScript is only capable of handling 53-bit numbers, if you are working with a big number such as Twitter ID, which is using 64-bit number, then you need to find an external library to do that, otherwise, there will be precision lost.
View in JSFiddle
<script type="text/javascript" src="big-number.js"></script>

<script type="text/javascript">
    (function () {
        var a = new BigNumber("07777777"), b = "888888880";
        console.log(a.multiply(b).toString());
        console.log(new BigNumber("990").toString());
    })();
</script>
Download Library

Saturday, March 9, 2019

ReactJS > Load Different Component Based on Different Conditions

I want to load different component based on URL or as I think, any different condition. So if URL is myreact.com/user/1000 it should load AdminUserComponent and if URL is myreact.com/user/5000 it should load StaffUserComponent. Its just an example, we can handle any type of conditions based on situation.
So our Route would be like

<Route path="/user/:user_param" component={UserDecideWrapper} />
And the UserDecideWrapper is nothing but a if else condition block to decide which component will load or not.

class ComponentDecide extends MainActivity {
    render() {
        let id = parseFloat(this.props.match.params.id);
        if (isNaN(id)) {
            return <Home {...this.props}/>
        }
        if (id === 1000) {
            return <AdminUserComponent {...this.props}/>
        }
        return <StaffUserComponent {...this.props}/>
    }
}
{...this.props} indicated that props will be passed as constructor.

Install ReactJS along with Laravel 5.X along with higher version such 6.X

We need npm command, so for this we need to install NodeJS first, this will create NPM along with this, for windows users, go to https://nodejs.org/en/ and download your suitable installer and install if not alredy installed..
Now we will create an Laravel project first using following command (this will take some time):
composer create-project --prefer-dist laravel/laravel ReactJSLaravelTutorial


Laravel installed:

Now we need to initiate scaffolding with React. Luckily for us, there is a preset Artisan command we can use for that. The preset command was added in Laravel 5.5, which allows us to specify our JavaScript framework of choice.

php artisan preset react

After that, we need to install the JavaScript dependencies of our project. By default, package.json file is there, so we just need to type the following command to get the NPM dependencies.

Please run npm install && npm run dev to compile your fresh scaffolding.
We should now have an Example.js file inside resources/assets/js/components, which is a basic React component. Also, resources/assets/js/app.js has been updated to make use of the Example component.

Now go to your database manager, for example, phpMyAdmin or MySQL work bench and create one database.
Go to .env file and enter your database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db-laravel1
DB_USERNAME=root
DB_PASSWORD=
Now we will create a model using command: php artisan make:model Project -m (this will create an migration script):

D:\all-my-php-projects\ReactJS\ReactJSLaravelTutorial>php artisan make:model Project -m
Model created successfully.
Created Migration: 2019_03_03_153423_create_projects_table

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    protected $fillable = ['name', 'description'];
}

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProjectsTable extends Migration
{
    public function up()
    {
        Schema::create('projects', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->text('description');
            $table->boolean('is_completed')->default(0);
            $table->timestamps();
        });
    }

    public function down()
    {
        
    }
}

And execute command php artisan migrate, this will create/modify table as needed.
We’ll start by defining the API endpoints. Open routes/api.php and replace it content with the code below:

<?php
Route::get('projects', 'ProjectController@index');
Route::post('projects', 'ProjectController@store');
Route::get('projects/{id}', 'ProjectController@show');
Route::put('projects/{project}', 'ProjectController@markAsCompleted');
Now we will create controller using command: php artisan make:controller ProjectController

<?php
namespace App\Http\Controllers;

use App\Project;
use Illuminate\Http\Request;

class ProjectController extends Controller
{
    public function index()
    {
        $projects = Project::where('is_completed', false)
            ->orderBy('created_at', 'desc')
            ->withCount(['tasks' => function ($query) {
                $query->where('is_completed', false);
            }])
            ->get();

        return $projects->toJson();
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required',
            'description' => 'required',
        ]);

        $project = Project::create([
            'name' => $validatedData['name'],
            'description' => $validatedData['description'],
        ]);

        return response()->json('Project created!');
    }

    public function show($id)
    {
        $project = Project::with(['tasks' => function ($query) {
            $query->where('is_completed', false);
        }])->find($id);

        return $project->toJson();
    }

    public function markAsCompleted(Project $project)
    {
        $project->is_completed = true;
        $project->update();

        return response()->json('Project updated!');
    }
}
We’ll be using React Router to handle routing in our application. For this, we need to render a single view file for all our application routes. Open routes/web.php and replace it content with the code below:

Route::view('/{path?}', 'app');
Next, let’s create the app.blade.php view file. We’ll create this file directly within the resources/views directory, then paste the following code in it:

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Project Management</title>
    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div id="app"></div>

<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
The App component will serve as the base for our React components. Let’s rename the default Example component to App and replace it content with the following code:
// resources/js/components/App.js

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import Header from './Header'
import ProjectsList from './ProjectsList'

class App extends Component {
    render () {
        return (
            <BrowserRouter>
                <div>
                    <Header />
                    <Switch>
                        <Route exact path='/' component={ProjectsList} />
                    </Switch>
                </div>
            </BrowserRouter>
        )
    }
}

ReactDOM.render(<App />, document.getElementById('app'));


Now install react router using command: npm install react-router-dom

update resources/assets/js/app.js as below:

require('./bootstrap');
require('./components/App');
Create a new Header.js file within the resources/js/components directory and paste the code below in it:

import React from 'react'
import { Link } from 'react-router-dom'

const Header = () => (
    <nav className='navbar navbar-expand-md navbar-light navbar-laravel'>
        <div className='container'>
            <Link className='navbar-brand' to='/'>Project Management</Link>
        </div>
    </nav>
);

export default Header
Create a new ProjectsList.js file within the resources/js/components directory and paste the code below in it:

import axios from 'axios'
import React, { Component } from 'react'
import { Link } from 'react-router-dom'

class ProjectsList extends Component {
    constructor () {
        super();
        this.state = {
            projects: []
        }
    }

    componentDidMount () {
        axios.get('/api/projects').then( response => {
            this.setState({
                projects: response.data
            })
        })
    }

    render () {
        const { projects } = this.state;
        return (
            <div className='container py-4'>
                <div className='row justify-content-center'>
                    <div className='col-md-8'>
                        <div className='card'>
                            <div className='card-header'>All projects</div>
                            <div className='card-body'>
                                <Link className='btn btn-primary btn-sm mb-3' to='/create'>
                                    Create new project
                                </Link>
                                <ul className='list-group list-group-flush'>
                                    {projects.map(project => (
                                        <Link
                                            className='list-group-item list-group-item-action d-flex justify-content-between align-items-center'
                                            to={`/${project.id}`}
                                            key={project.id}>
                                            {project.name}
                                            <span className='badge badge-primary badge-pill'>{project.tasks_count}</span>
                                        </Link>
                                    ))}
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

export default ProjectsList
This is the basic structure for ReactJS with Laravel. Execute php artisan serve to start server.
Some sample screen shots:



Run command npm run dev (for windows user, run command as an administrator) to compile ReactJS code once you made some changes.

Below is GitHub link of this project:

https://github.com/pritomkucse/reactjs-with-laravel-6.X

After download source from GitHub run command composer install to install laravel dependencies, then run php artisan migrate for database migration (but make sure you configure database in .env file) and then run npm install to install ReactJS dependencies. Finally run npm run dev to package ReactJS and then browser your project directory. That's all.


Sample .env File
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:PuBBf9PHnf4RkJokRNDMeTDY6SWWr8s2TilF9E3b4Fs=
APP_DEBUG=true
APP_URL=http://react-with-laravel.com
APP_PATH=/

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db-laravel1
DB_USERNAME=root
DB_PASSWORD=1234

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

Sample Virtual Host File

<VirtualHost react-with-laravel.com:80>
    DocumentRoot "C:\Users\PRITOM\Desktop\MINE\reactjs-with-laravel-6.X\public"
    ServerName react-with-laravel.com
    ErrorLog "logs/react-with-laravel.com-error.log"
    CustomLog "logs/react-with-laravel.com-access.log" combined
    <Directory "C:\Users\PRITOM\Desktop\MINE\reactjs-with-laravel-6.X">
        Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
            Require all granted
    </Directory>
</VirtualHost>